准备好的语句中 bind_param() 的错误报告

error reporting for bind_param() in prepared statements

我想捕捉这个错误:

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables

一个解决方案是 provided here,但由于某种原因它没有捕捉到错误。

$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc returns 1 即使绑定参数个数不匹配...

首先,你不能在这样的情况下捕获这样的警告。仅仅因为它是在 bind_param 行上引发的,因此它发生在下面的检查条件之前。

因此,您可能会感到困惑 - 条件正常,但为时已晚。

我建议使用简单的错误处理程序捕获所有错误。这个问题不是mysqli特有的,通常你想捕获所有警告和其他错误并统一处理。您可以在我关于 PHP error reporting:

的文章中找到示例
set_error_handler("myErrorHandler");
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    error_log("$errstr in $errfile:$errline");
    header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
    readfile("500.html");
    exit;
}

它会完全按照您的条件执行,但无需在每次准备 SQL 查询时都编写这样的条件。