Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Transactions in mysql via php

Tags:

php

mysql

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

like image 976
Duahs Avatar asked Jul 12 '13 22:07

Duahs


2 Answers

$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

like image 111
Mark Baker Avatar answered Oct 24 '22 02:10

Mark Baker


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.

like image 20
jcsanyi Avatar answered Oct 24 '22 02:10

jcsanyi