繁体   English   中英

通过php在mysql中实现事务

[英]Implementing Transactions in mysql via php

以下是我的疑问

 $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查询中实现事务,我想在其中一个查询失败时失败所有查询。 上面的代码抛出一个错误(“致命错误:调用未定义的方法mysqli :: beginTransaction()”)。请有任何更好的解决方案或想法来解决问题。谢谢你的帮助

$db->begin_transaction();

$db->beginTransaction();

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

如果早于PHP 5.5,那么使用

$db->autocommit(true);

代替

根据文档, begin_transaction()是PHP 5.5中的新增功能。 (刚刚几周前发布)

如果您收到错误消息,表明它不存在,则可能意味着您使用的是旧版本的PHP。

如果您认为自己运行的是PHP 5.5,请通过在同一脚本中运行此版本来验证您的PHP版本:

echo(phpversion());

有时,机器上存在多个版本的PHP,并且您的脚本实际上可能不会在您认为的版本中执行。

您可以实现$ count,类似于:

$err_count = 0;
$query1 = "insert into table1(id,name) values('1','Dan')";
if(!$query1) 
    $err_count++;

if($err_count>0) 
    throw new Exception("error msg");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM