PHP prepared statements and transactions in a loop(PHP 在循环中准备语句和事务)
问题描述
循环代码中的经典事务:
The classic transactions in a loop code:
$mysqli->query("START TRANSACTION");
foreach ($pdata as $key => $value) {
$sql = "INSERT INTO temp (`fund_id`) VALUES (" . $value . ")";
$result = $mysqli->query($sql);
}
$mysqli->query("COMMIT");
然后我们更改为准备好的语句:
Then we change to prepared statements:
$mysqli->autocommit(FALSE);
foreach ($pdata as $key => $value) {
$sql = "INSERT INTO temp (`fund_id`) VALUES (?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $value);
$stmt->execute();
}
$mysqli->commit();
问题:
1) 这两个代码是否相同?我是否在带有准备好的语句的第二个代码中遗漏了什么?
1) Are these two codes identical? Am I missing something in the second code with prepared statements?
2) $mysqli->commit() 和 $mysqli->query("COMMIT") 一样吗?
2) Is $mysqli->commit() the same as $mysqli->query("COMMIT")?
3) 我是否需要为准备好的语句块添加 $mysqli->query("START TRANSACTION"); 或者当我们设置 autocommit(FALSE) 时事务将自动启动)?
3) Do I need to add $mysqli->query("START TRANSACTION"); for the prepared statements block or the transaction will automatically start when we set autocommit(FALSE)?
推荐答案
可以通过将 prepare 和 bind_param 语句拉出循环来优化循环.>
Your loop can be optimized by pulling the prepare and bind_param statements out of the loop.
$value = null;
$mysqli->autocommit(FALSE);
$sql = "INSERT INTO temp (`fund_id`) VALUES (?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $value);
foreach ($pdata as $value) {
$stmt->execute();
}
$mysqli->commit();
您已使用 autocommit(FALSE) 行关闭自动提交,因此不需要使用 START TRANSACTION 语句.
You have turned off autocommit with your autocommit(FALSE) line and therefore don't need to use the START TRANSACTION statement.
这篇关于PHP 在循环中准备语句和事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 在循环中准备语句和事务
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
