Reputation: 15673
I have a typical transaction of
START TRANSACTION
INSERT INTO ...
UPDATE ...
DELETE ...
COMMIT
Problem 1: Failure in UPDATE
will not block the transaction. In single query, I use mysql_affected_rows()
to inspect the success of UPDATE
but how to do so in the middle of a Transaction?
Problem 2: How to detect which query caused the transaction stop? To make a if condiction in PHP
?
Upvotes: 1
Views: 995
Reputation: 270599
Assuming you are using the mysql_*()
functions based on your mention of mysql_affected_rows()
, you should simply be calling each stage of the transaction in its own mysql_query()
and checking its success or failure at each stage. Unless you wrap this as a stored procedure, you have to call these as individual statements since mysql_query()
doesn't support multiple statements in one call.
function doTransaction() {
mysql_query("START TRANSACTION;");
$ins = mysql_query("INSERT INTO ....");
if (!$ins) {
// fail
mysql_query("ROLLBACK");
return FALSE;
}
$upd = mysql_query("UPDATE...");
if (!$upd) {
// fail
mysql_query("ROLLBACK");
return FALSE;
}
if (mysql_affected rows() === 0) {
// no rows updated, rollback if necessary
mysql_query("ROLLBACK");
return FALSE;
}
$del = mysql_query("DELETE FROM...");
if (!$del) {
// fail
mysql_query("ROLLBACK");
return FALSE;
}
// All succeeded
mysql_query("COMMIT");
return TRUE;
}
Upvotes: 2