简体   繁体   中英

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. 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

$db->begin_transaction();

not

$db->beginTransaction();

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

If earlier than PHP 5.5, then use

$db->autocommit(true);

instead

According to the documentation, begin_transaction() is new in 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.

If you think you are running PHP 5.5, please verify your PHP version by running this earlier in your same script:

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.

You could implement a $count, something like that:

$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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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