我正试着了解MySQli,我被错误报告搞糊涂了.

$stmt_test =  $mysqliDatabaseConnection->stmt_init();
if($stmt_test->prepare("INSERT INTO testtable VALUES (23,44,56)"))
{
 $stmt_test->execute();
 $stmt_test->close();
}
else echo("Statement failed: ". $stmt_test->error . "<br>");

但是,PREPARE语句的返回值是否只检测SQL语句的准备过程中是否存在错误,而不检测执行错误?如果是这样,我是否应该将EXECUTE行更改为也标记错误,如下所示:

if($stmt_test->execute()) $errorflag=true;

为了安全起见,我应该在语句执行后执行以下操作:

if($stmt_test->errno) {$errorflag=true;}

...或者我可以开始了吗?MySQLi prepare语句上的返回值捕获了与它定义的查询的完整执行相关的所有错误?

谢谢

推荐答案

mysqli的每种方法都可能失败.您应该测试每个返回值.如果一个失败了,想想继续使用一个不在你期望状态的对象是否有意义.(可能不是处于"安全"状态,但我认为这不是问题.)

因 for each 连接/语句只存储最后一个操作的错误消息,所以如果您在出错后继续操作,您可能会丢失关于导致错误的what的信息.您可能希望使用该信息让脚本决定是重试(仅是临时问题)、更改某些内容还是完全退出(并报告错误).而且它使调试变得容易得多.

$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();

六年后的几句话...

The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....

Php相关问答推荐

如何使用查询范围在Statamic中按组过滤用户?

产品ACF值在WooCommerce我的账户订单的附加列中为空

如何在WordPress中为特定自定义帖子类型自定义URL struct

如果再次调用SESSION_START(),会话.gc-max是否会重新启动?或者它是从第一次创建会话开始计算的?

PHP DateInterval天数不一致

在内部API请求之后,在响应客户端之前,是否忘记了PHP中的Header()?

使用正则表达式搜索两个子字符串(没有重叠/共享字符)

如何确保所有语言文件都使用Laravel中的新密钥进行更新?

无法使用php IMAP从Gmail获取收件箱

laravel中获取的数据会自动更改时间戳值

在WooCommerce上克隆订单时使用`add_product()`添加产品元数据

在指定的约束内使用随机量填充数据集

是否有条件判断是否发布了另一个Wordpress页面?

PHP 数组中第一级 node 到 XML 的唯一名称

woocommerce_available_ payment_gateways 过滤器挂钩多次触发

如何在 Laravel 迁移中使用日期时间和天数?

计算添加到购物车的点击次数并将其显示在 WooCommerce 管理产品列表中

产品页面自定义复选框可对 WooCommerce 购物车小计启用百分比折扣

如何正确判断 PHP 是否已正确配置为使用 DOMDocument?

路由未定义的 laravel 导出