mysqli - handling errors with transactions

假如想象 提交于 2019-12-25 07:48:23

问题


How to properly handle errors with transactions and prepared statements when using mysqli?

Snippet:

<?php
$conn = require_once 'dbconn.php';
$conn->autocommit(FALSE);

$stmt_ins_option = $conn->prepare('INSERT INTO options(option_name) VALUES(?)');
$option_name = 'foo';
$stmt_ins_option->bind_param('s', $option_name);
$stmt_ins_option->execute();
$conn->commit();
if($conn->errno) {
    $conn->rollback();
    echo $conn->error;
}

It won't add it a second time because there's a UNIQUE constraint on that column.

However the script won't report any error either.

What am I missing?


回答1:


execute returns false on failure, so you may want to check it before committing. Also, rolling back in your code has no effect because you committed transaction previously. I'd write something like

try
{
  ....
  if (!$stmt_ins_option->execute())
  {
   throw new Exception("Cannot insert record. Reason :".$stmt_ins_option->error);
   // surely, it's better to define your own exception hierarchy
  }
  $conn->commit();
}
catch (Exception $e)
{
   $conn->rollback();
   // display error/re-raise/ or whatever you think makes sense for your function
}



回答2:


Is there any way to make mysqli classes throw exceptions instead of me having to check for errors every time

According to this answer you can use the following call to enable exceptions for such errors:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

See mysqli_driver::$report_mode

(Stupid Stack Overflow not letting me make comments)



来源:https://stackoverflow.com/questions/9350452/mysqli-handling-errors-with-transactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!