首页 > 解决方案 > 准备好的语句中的 bind_param() 错误报告

问题描述

我想捕捉这个错误:

警告:mysqli_stmt::bind_param():类型定义字符串中的元素数与绑定变量数不匹配

这里提供了一个解决方案,但由于某种原因它没有捕获错误。

$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即使绑定参数的数量不匹配,也返回 1...

标签: phpmysqliprepared-statement

解决方案


首先,你不能在这样的条件下捕捉到这样的警告。仅仅因为它是在线上提出的,bind_param因此它发生在下面的检查条件之前。

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

我建议使用简单的错误处理程序来捕获所有错误。问题不是特定于 mysqli,通常您希望捕获所有警告和其他错误并统一处理。您可以在我关于PHP 错误报告的文章中找到一个示例:

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 查询时都编写这样的条件。


推荐阅读