mysqli-处理交易错误 [英] mysqli - handling errors with transactions

查看:61
本文介绍了mysqli-处理交易错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用mysqli时如何正确处理事务和预准备语句的错误?

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

摘要:

<?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;
}

它不会再添加一次,因为该列上有一个UNIQUE约束.

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.

我想念什么?

推荐答案

execute失败时返回false,因此您可能需要在提交之前进行检查.同样,回滚代码也无效,因为您之前已提交事务.我会写类似的东西

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
}

这篇关于mysqli-处理交易错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆