1

I'm using MySQL and PHP.

Running this transaction:

begin;
....
commit;

How should I judge whether it failed in PHP?

user198729
  • 61,774
  • 108
  • 250
  • 348

3 Answers3

1

Check the result (mysql_query, PHP Manual):

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

Example (PHP4-style): EDIT: Improved example per johannes's comment

mysql_connect("localhost", "username", "password") or die( mysql_error() );

mysql_select_db("test") or die(mysql_error());

$query = "INSERT INTO ..."; //Query here

mysql_query("BEGIN"); // transaction begins

$result = mysql_query($query);

if(!$result)
{
    mysql_query("ROLLBACK"); //Transaction rolls back
    echo "Rolled Back.";
    exit;
}
else 
{
    $committed = mysql_query("COMMIT"); //Commit Transaction
    if(!$committed)
    {
        //Commit Failed, take appropriate action
    }
    else
    {
        echo "Successful Insert.";
    }
}

Or, for PDO usage, SEE PDO try-catch usage in functions

Community
  • 1
  • 1
micahwittman
  • 12,356
  • 2
  • 32
  • 37
  • Do not use the @ operatorin such an excessive way. this makes debugging really hard. Instead set display_errors to off and log the errors to a logfile. and you're not checking whether the commit succeeds ... – johannes Dec 24 '09 at 09:21
0

In general you should expect an error to be returned from the database if the transaction fails same as if you try and execute a single duff query.

Note that not all MySQL table types support transactions.

Paolo
  • 22,188
  • 6
  • 42
  • 49
0

After each executed SQL, check that the DB did not return an error. Use http://www.php.net/manual/en/function.mysql-errno.php to check for errors.

The DB may return errors at any point, and every SQL should always be checked anyways...

Quamis
  • 10,924
  • 12
  • 50
  • 66