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