我正在努力弄清MySQli,但我对错误报告感到困惑。我正在使用MySQLi'prepare'语句的返回值来检测执行SQL时的错误,如下所示:
$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 . "
"); 但是,prepare语句的返回值是否仅检测SQL语句的前置是否存在错误,而不检测执行错误?如果是这样,我应该将执行行更改为标记错误,如下所示:
if($stmt_test->execute()) $errorflag=true; 为了安全起见,在语句执行后我还应该执行以下操作:
if($stmt_test->errno) {$errorflag=true;} ...还是我可以从头开始,MySQLi prepare'语句的返回值捕获了与它定义的查询的完整执行相关的所有错误?
谢谢C
我在过去两天里写了两次(对我来说,这是重复的,即使问题开始有所不同)。
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();来源:stack overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。