你能一起使用Mysqli准备,执行和回滚吗?

时间:2012-10-09 20:00:53

标签: php mysqli execute rollback prepare

我想知道的是,你是否可以一起使用mysqli的prepareexecuterollback

$m = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);

$m->autocommit(FALSE);
$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
$query_ok = $stmt->execute();

$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
if ($query_ok) {$query_ok = $stmt->execute();}

if (!$query_ok) {$m->rollback();} else {$m->commit();}
你能做到吗?让我们假设上面的代码有一个循环和/或变量在其中获取新数据。

1 个答案:

答案 0 :(得分:0)

处理此问题的最佳方法是使用异常(一如既往,禁止PHP错误/警告内容)。仅仅因为我们的commit()电话可能也会失败。请注意,finally仅适用于较新的PHP版本。

<?php

// Transform all errors to exceptions!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
  $connection = new \mysqli($dbhost, $dbuser, $dbpassword, $dbname);
  $connection->autocommit(false);

  $stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
  $stmt->bind_param("ssi", $name, $gender, $age);
  $stmt->execute();

  // We can simply reuse the prepared statement if it's the same query.
  //$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");

  // We can even reuse the bound parameters.
  //$stmt->bind_param("ssi", $name, $gender, $age);

  // Yet it would be better to write it like this:
  /*
  $stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?), (?, ?, ?)");
  $stmt->bind_param("ssissi", $name, $gender, $age, $name, $gender, $age);
   */

  $stmt->execute();
  $stmt->commit();
}
catch (\mysqli_sql_exception $exception) {
  $connection->rollback();
  throw $exception;
}
finally {
  isset($stmt) && $stmt->close();
  $connection->autocommit(true);
}