我正在尝试使用异常验证我的 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>";
}
最佳答案
想必你想输出异常?做:
echo $e->getMessage();
编辑:为了回应您稍后关于脚本结束的评论,将 MySQL 查询放在 try block 中。
编辑 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();
}
}
关于php脚本不会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9852352/