php - 通过php在mysql中实现事务

标签 php mysql

下面是我的问题

 $db= new mysqli('localhost','user','passcode','dbname');
try {
// First of all, let's begin a transaction
$db->beginTransaction();

// A set of queries; if one fails, an exception should be thrown
$query1="insert into table1(id,name) values('1','Dan')";
$query2="insert into table2(id,name) values('2','Anaba')";

// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$db->commit();

} catch (Exception $e) {
// An exception has been thrown
// We must rollback the transaction
$db->rollback();
}

拜托,我正在尝试通过 php 在 mysql 查询中实现事务,当其中一个查询失败时,我想使所有查询失败。上面的代码抛出一个错误(“ fatal error :调用未定义的方法mysqli::beginTransaction()”)。请问有没有更好的解决方案或想法来解决这个问题。谢谢你的帮助

最佳答案

$db->begin_transaction();

不是

$db->beginTransaction();

http://www.php.net/manual/en/mysqli.begin-transaction.php

如果早于 PHP 5.5,则使用

$db->autocommit(true);

代替

关于php - 通过php在mysql中实现事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17625016/

相关文章:

php - DOMXPath 根据先前的同级值获取同级

php - 当限制达到 4 时更改 SQL 查询

php - 在 PHP 中 while/foreach 内包装 3 个或更少的对象

mysql - 在 MySQL 中设置最终一致性(延迟提交)

mysql - 为什么加载环境变量主函数golang

php - 如何避免 Request Entity Too Large 413 错误

php - 未捕获的运行时异常 : Unable to load ZF2 Run `php composer.phar install`

C# MySql参数问题

php - Codeigniter 返回自定义 ID

jquery - SQL 子查询传递数据