return false 为什么抓不到mysqli_stmt::prepare?

Why mysqli_stmt::prepare cannot be catched when return false?

我有这样的代码,故意造成查询错误: 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:\xampp\htdocs\delete_test.php:56 Stack trace: #0 C:\xampp\htdocs\delete_test.php(56): mysqli_stmt->prepare('xSELECT * FROM ...') #1 {main} thrown in C:\xampp\htdocs\delete_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 可以触发异常,就像您收到的异常一样,它告诉您的信息远不止 "There is something wrong #1"

你有 3 行代码,你把它变成了 12 行代码,你仍然没有在 if 语句中包装 stmt_init()bind_param()。只需坚持简单的三行准备好的语句。

$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 调用!