php脚本不会抛出异常

标签 php mysql forms exception

我正在尝试使用异常验证我的 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/

相关文章:

php - 单选按钮显示悬停在两个单选按钮之间使用 jquery

mysql - 如何用 UNION 运算符替换 OR 运算符?

php - 无法抛出错误消息

php - 黑钻问号与某些字符的丢失

mysql - 如何在检索数据时删除重复的行

mysql - 图表 Sonar Qube 数据库

C# 动态窗体帮助

javascript - 带有表单的 Angular 旁模态窗口。当我取消\关闭窗口时正在提交表单

javascript - jquery 从 6 种形式中只选择一个 radio

php - jQuery 等待服务器响应超时