我在最近两天之前写了两次这样的话(对我而言,即使问题开始有点不同,也是重复的).
mysqli的每种方法都可能失败.您应该测试每个返回值.如果一个失败,请考虑继续使用不符合您期望状态的对象是否有意义. (可能不是处于“安全”状态,但我认为这不是问题.)
由于每个连接/语句仅存储最后一个操作的错误消息,因此如果在出现错误后继续,则可能会丢失有关导致错误的原因的信息.您可能希望使用该信息让脚本决定是再次尝试(仅限临时问题),更改内容还是完全拯救(并报告错误).它使调试变得更容易.
$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$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 = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
编辑:六年后的几个笔记….
mysqli扩展完全能够通过异常报告导致(mysqli)错误代码不是0的操作,参见mysqli_driver::$report_mode.
die()真的非常粗糙,即使是像这样的例子我也不会用它.
所以,请注意,每个(mysql)操作都会因为多种原因而失败;即使完全相同的事情在之前进行了一千次……