为什么当返回false时无法捕获mysqli_stmt::prepare



我有这样的代码,并故意使查询出错:delete_test.php.

<?php
.....
$id = 1;
$sql = "xSELECT * FROM tbl_1 WHERE 1 AND id =?"; // Adding and an x to make this error
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($sql)){ // Line 56
echo "There is something wrong #1";
exit();
}else{
$stmt->bind_param("i", $id);
if(!$stmt->execute()){
echo "There is something wrong #2";
exit();
}
.....
}
.....
?>

当我运行delete_test.php时,我得到了这个错误:

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'xSELECT * FROM tbl_1 WHERE 1 AND id =?' at line 1 in C:xampphtdocsdelete_test.php:56 Stack trace: #0 C:xampphtdocsdelete_test.php(56): mysqli_stmt->prepare('xSELECT * FROM ...') #1 {main} thrown in C:xampphtdocsdelete_test.php on line 56

而不是打印这个:

There is something wrong #1

为什么php忽略了echo "There is something wrong #1";所在行的错误?

以及如何使echo "There is something wrong #1";打印在哪一行的行错误?

不能用if语句捕获异常!

绝对没有理由将每个mysqli函数调用封装在if语句中,即使您要关闭mysqli错误报告。Mysqli可以触发像您收到的异常一样的异常,它告诉您的不仅仅是"有问题#1"。

您有3行代码,并将其转换为12行代码,但仍然没有将stmt_init()bind_param()封装在if语句中。只要坚持简单的三行准备好的陈述。

$stmt = $mysqli->prepare("xSELECT * FROM tbl_1 WHERE 1 AND id =?");
$stmt->bind_param('s', $id);
$stmt->execute();

PHP有内置的错误处理程序,因此如果发生错误,它可以将其显示给最终用户,也可以将错误记录在服务器上的文件中。后者是优选的。如果您想使用自己的错误处理程序,那么您可以将所有PHP代码封装在try-catch块中,并使用自定义记录器处理所有异常和错误。不要在try-catch中包装每个mysqli调用!

最新更新