我尝试使用异常来验证我的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>";
}发布于 2012-03-24 22:06:45
假设您想输出异常?执行以下操作:
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();
}
}发布于 2012-03-24 22:05:58
您正在捕获它并执行一条几乎什么也不做的语句。
$e->getMessage();只是将其作为字符串获取,并将其丢弃,而不进行回显。
要么回显它,要么重新抛出异常,或者,如果您只想在此时退出,则根本不捕获异常(您可以删除try和catch块)。
发布于 2012-03-24 22:06:56
它是这样做的,但是除了捕获它之外,您并没有对异常做任何事情。
试一试
echo $e->getMessage()https://stackoverflow.com/questions/9852352
复制相似问题