Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & mySQL: Simple code to implement Transaction - Commit & Rollback

MY PLATFORM:

PHP & mySQL

MY SITUATION:

I am trying to implement transactions within my code. I tried to follow examples, but it's not much help. I am running 3 queries and I wanted to write a transaction in such a way so that if any of the query(ies) fail, the whole transaction should roll back. I would really appreciate a simple, efficient and non-object oriented PHP code to achieve this goal. Thank you in advance.

MY PHP CODE:

//db_res calls a custom function that performs a mysql_query on the query
$res1 = db_res("SELECT c1, c2 FROM t1 WHERE c5 = 3");
$res2 = db_res("UPDATE t2 SET c1 = 5 WHERE c2 = 10");
$res3 = db_res("DELETE FROM t3 WHERE c1 = 20");

if( $res1 && $res2 && $res3 )
{
 //commit --- but how?
}
else
{
 //rollback --- but how?
}
like image 860
Devner Avatar asked Jan 25 '10 15:01

Devner


People also ask

What is PHP is used for?

PHP (Hypertext Preprocessor) is known as a general-purpose scripting language that can be used to develop dynamic and interactive websites. It was among the first server-side languages that could be embedded into HTML, making it easier to add functionality to web pages without needing to call external files for data.

What coding is PHP?

PHP is a server side scripting language. that is used to develop Static websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home Pages. PHP scripts can only be interpreted on a server that has PHP installed.


1 Answers

You don't need to use mysqli. You can just issue the transaction commands as queries.

So for your example:

mysql_query("start transaction;");

//db_res calls a custom function that performs a mysql_query on the query
$res1 = db_res("SELECT c1, c2 FROM t1 WHERE c5 = 3");
$res2 = db_res("UPDATE t2 SET c1 = 5 WHERE c2 = 10");
$res3 = db_res("DELETE FROM t3 WHERE c1 = 20");

if( $res1 && $res2 && $res3 )
{
  mysql_query("commit;");
}
else
{
  mysql_query("rollback;");
}

By they way if you are thinking about upgrading to mysqli, please don't. Upgrade to PDO instead, it's much more sane.

like image 126
rjmunro Avatar answered Sep 28 '22 04:09

rjmunro