PHP MySQLi一个准备失败的查询将杀死脚本中所有未来的代码/查询


PHP MySQLi A failed prepared query will kill all future code/queries in the script

我正试图弄清楚应该如何解决这个问题。当我有一个MySQLi查询失败时,它会自动终止脚本的其余部分。例如

//Pure example code
$data = $mysqli->prepare("somequery");
$data->execute(); // Execute the prepared query.
//If the query above fails, the rest of the script doesn't get executed.

基本上,我想知道如何在查询失败时阻止PHP杀死脚本。有什么想法吗?由于假定的性能和安全收益,我转而使用事先准备好的报表。重写所有内容以计划旧查询将是一件痛苦的事情。

谢谢,

您需要实际检查是否成功,而不是在data可能是false时盲目执行$data->execute(),这将引发错误并中止脚本。

从文档中,prepare。。。

返回一个语句对象,如果发生错误则返回FALSE。

PHP在致命错误时杀死脚本。如果该线路出现故障:

$data = $mysqli->prepare("somequery");

PHP不会杀死您的脚本,但$data设置为false。脚本将在下一行被杀死:

$data->execute();

出现以下错误:

Fatal error: Call to a member function execute() on a non-object in...

首先,您需要启用error_reporting,这样您就可以自己诊断问题(也许还可以找到解决方案(。其次,正如@meaviar所提到的,检查mysqli函数的返回值:

$data = $mysqli->prepare("somequery");
if($data === false) {
    echo $mysqli->error;
    // dying isn't the most graceful approach by the way
    die();
}
if($data->execute() === false) {
    echo $mysqli->error;
    die();
}

从mysql_*更改为mysqli与您的问题无关。如果您使用的是mysql_*,那么您仍然需要检查函数的返回值。一条通用规则:永远不要假设您的查询总是成功的。

if($data = $mysqli->prepare("somequery")) {
// binding
  $data->execute(); // Execute the prepared query.
}

从文档