php返回mysql错误语句_php – MySQLi编写语句错误报告

我在最近两天之前写了两次这样的话(对我而言,即使问题开始有点不同,也是重复的).

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)操作都会因为多种原因而失败;即使完全相同的事情在之前进行了一千次……

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值