【问题标题】:error reporting for bind_param() in prepared statements准备好的语句中的 bind_param() 错误报告
【发布时间】:2019-06-26 07:47:27
【问题描述】:

我想捕捉这个错误:

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

解决方案是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即使绑定参数个数不匹配也返回1...

【问题讨论】:

  • 我无法重现这个。如果bind_param 失败,我总是得到false 结果
  • 我支持这个^
  • 因此,如果我编辑代码以删除参数: $rc = $stmt->bind_param('iii', $x, $y);我收到警告,无法检查 $rc 是否为假。可能是我误会了?

标签: php mysqli prepared-statement


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2014-06-11
    相关资源
    最近更新 更多