简体   繁体   English

通过php在mysql中实现事务

[英]Implementing Transactions in mysql via php

Below are my queries 以下是我的疑问

 $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();
}

Please I am trying to implement transaction in mysql queries through php, I would like to fail all queries when one of the queries fail. 请问我试图通过php在mysql查询中实现事务,我想在其中一个查询失败时失败所有查询。 The above code throws an error("Fatal error: Call to undefined method mysqli::beginTransaction()").Please is there any better solution or idea to solve the problem.Thanks for your help 上面的代码抛出一个错误(“致命错误:调用未定义的方法mysqli :: beginTransaction()”)。请有任何更好的解决方案或想法来解决问题。谢谢你的帮助

$db->begin_transaction();

not

$db->beginTransaction();

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

If earlier than PHP 5.5, then use 如果早于PHP 5.5,那么使用

$db->autocommit(true);

instead 代替

According to the documentation, begin_transaction() is new in PHP 5.5. 根据文档, begin_transaction()是PHP 5.5中的新增功能。 (just released a couple weeks ago) (刚刚几周前发布)

If you're getting an error saying that it doesn't exist, it probably means you're using an older version of PHP. 如果您收到错误消息,表明它不存在,则可能意味着您使用的是旧版本的PHP。

If you think you are running PHP 5.5, please verify your PHP version by running this earlier in your same script: 如果您认为自己运行的是PHP 5.5,请通过在同一脚本中运行此版本来验证您的PHP版本:

echo(phpversion());

Sometimes there's multiple versions of PHP present on a machine, and your script may not actually be executing in the version that you think it is. 有时,机器上存在多个版本的PHP,并且您的脚本实际上可能不会在您认为的版本中执行。

You could implement a $count, something like that: 您可以实现$ 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