gpt4 book ai didi

php - mysqli准备好的语句和事务可以一起使用吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:50:37 25 4
gpt4 key购买 nike

我想知道的是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();}

你能做到吗?让我们假设上面的代码有一个循环和/或变量在其中获取新数据。

最佳答案

处理此问题的最佳方法是处理异常(一如既往,该死的 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();
$connection->commit();
}
catch (\mysqli_sql_exception $exception) {
$connection->rollback();
throw $exception;
}
finally {
isset($stmt) && $stmt->close();
$connection->autocommit(true);
}

关于php - mysqli准备好的语句和事务可以一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12807555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com