Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement commit/rollback for MySQL in PHP?

Well basically I have this script that takes a long time to execute and occasionally times out and leaves semi-complete data floating around my database. (Yes I know in a perfect world I would fix THAT instead of implementing commits and rollbacks but I am forced to not do that)

Here is my basic code (dumbed down for simplicity):

$database = new PDO("mysql:host=host;dbname=mysql_db","username","password");

while (notDone())
{
    $add_row = $database->prepare("INSERT INTO table (columns) VALUES (?)");
    $add_row->execute(array('values'));

    //PROCESSING STUFF THAT TAKES A LONG TIME GOES HERE
}

$database = null;

So my problem is that if that if the entire process within that while loop isn't complete then I don't want the row inserted to remain there. I think that somehow I could use commits/rollbacks at the beginning and end of the while loop to do this but don't know how.

like image 887
Andrew G. Johnson Avatar asked Nov 30 '08 23:11

Andrew G. Johnson


People also ask

How do I ROLLBACK a commit in MySQL?

A COMMIT or ROLLBACK statement ends the current transaction and a new one starts. If a session that has autocommit disabled ends without explicitly committing the final transaction, MySQL rolls back that transaction.

How do I ROLLBACK a commit transaction?

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.


3 Answers

Take a look at this tutorial on transactions with PDO.

Basically wrap the long running code in:

$dbh->beginTransaction();
...
$dbh->commit();

And according to this PDO document page:

"When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. "

So you will lose the transaction that was pending when the script timed out.

But really, you ought to redesign this so that it doesn't depend on the scriipt staying alive.

like image 172
Brian C. Lane Avatar answered Oct 12 '22 03:10

Brian C. Lane


You need to use InnoDB based tables for transactions then use any library like PDO or MySQLi that supports them.

like image 37
Coder2000 Avatar answered Oct 12 '22 04:10

Coder2000


try
{
    $mysqli->autocommit(FALSE);
    $mysqli->query("insert into tblbook (id,cid,book) values('','3','book3.1')");
    echo $q_ins=$mysqli->affected_rows."<br>";
    $mysqli->query("update tblbook set book='book3' where cid='3'");
    echo $q_upd=$mysqli->affected_rows."<br>";
    $mysqli->commit();
}
catch(PDOException $e)
{
    $mysqli->rollback();
    echo $sql . '<br />' . $e->getMessage();
}
like image 42
Neelesh Avatar answered Oct 12 '22 03:10

Neelesh