I have a php file which performs a series of insert queries. If any of the queries generates an error, I would like to return the error message and query string and roll back all the queries
So far I have this:
mysql_query("SET autocommit=0;");
mysql_query("BEGIN;");
$sql ="SOME MALFORMED QUERY";
mysql_query($sql);
if(mysql_error()){
mysql_query("rollback;");
$arr = array("returnCode" => 0, "returnMessage" => "Query failed: " .$sql. mysql_error());
echo json_encode($arr);
die();
}
However, In javascript all I’m seeing returned in the return message JSON field is ‘Query failed: ‘. Any idea why this is?
The problem is with your
ROLLBACKquery: as explained in the manual, mysql_error returns the error text from the last MySQL function. Since you used mysql_query again, the previous error is lost.I suggest this code:
Executing
ROLLBACKin case an error occurs seems useless. The manual explains:Rolling back can be a slow operation that may occur implicitly without the user having explicitly asked for it (for example, when an error occurs)
The following code should then be enough: