我试图使用异常验证我的php表单,但不知怎么的,它不起作用。如果用户在"nameg"中输入任何非字符串的字符,在"amountg"中键入任何非整数的字符,则应该引发异常。在这种情况下是否应使用例外:
if(!empty($_POST['nameg']) && !empty($_POST['amountg']))
{
$user="rootdummy";
$pass="password";
$db="practice";
$nameg=$_POST['nameg'];
$amountg=$_POST['amountg'];
try{
if(!is_int($amountg) || !is_string($nameg)){
throw new Exception("This is the exception message!");
}
}
catch (Exception $e){
$e->getMessage();
}
mysql_connect('localhost',$user,$pass) or die("Connection Failed!, " . mysql_error());
$query="INSERT INTO practable (name,given) VALUES('$nameg',$amountg) ON DUPLICATE KEY UPDATE name='$nameg', given=IFNULL(given + $amountg,$amountg)";
mysql_select_db($db) or die("Couldn't connect to Database, " . mysql_error());
mysql_query($query) or die("Couldn't execute query! ". mysql_error());
mysql_close() or die("Couldn't disconnect!");
include("dbclient.php");
echo "<p style='font-weight:bold;text-align:center;'>Information Added!</p>";
}
您想输出异常吗?Do:
echo $e->getMessage();
编辑:为了回应您稍后关于脚本结束的评论,请将MySQL查询放在try块中。
编辑2:根据您的评论更改了验证。
if(!empty($_POST['nameg']) && !empty($_POST['amountg']))
{
$user="rootdummy";
$pass="password";
$db="practice";
$nameg=$_POST['nameg'];
$amountg=$_POST['amountg'];
try{
if(!ctype_numeric($amountg) || !ctype_alpha($nameg)){
throw new Exception("This is the exception message!");
}
mysql_connect('localhost',$user,$pass) or die("Connection Failed!, " . mysql_error());
$query="INSERT INTO practable (name,given) VALUES('$nameg',$amountg) ON DUPLICATE KEY UPDATE name='$nameg', given=IFNULL(given + $amountg,$amountg)";
mysql_select_db($db) or die("Couldn't connect to Database, " . mysql_error());
mysql_query($query) or die("Couldn't execute query! ". mysql_error());
mysql_close() or die("Couldn't disconnect!");
include("dbclient.php");
echo "<p style='font-weight:bold;text-align:center;'>Information Added!</p>";
}
catch (Exception $e){
echo $e->getMessage();
}
}
确实如此,但除了捕获异常之外,您什么也没做。
尝试
echo $e->getMessage()
您正在捕获它并执行一个几乎不起任何作用的语句。
$e->getMessage();
只是将其作为字符串获取并丢弃,而不进行回显。
要么回显它,要么重新抛出,或者,如果你只是想在那一点上退出,就不要捕获异常(你可以删除try和catch块)。