views:

170

answers:

1

I am going through this tutorial about PDO and have come to the point about transactions. Skipping the connection parts, I have this php code:

try
{
    $db->beginTransaction();

    $db->exec('DROP TABLE IF EXISTS animals');

    $db->exec('CREATE TABLE animals ('
        .'animal_id MEDIUMINT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,'
        .'animal_type VARCHAR(25) NOT NULL,'
        .'animal_name VARCHAR(25) NOT NULL)'
        .'ENGINE=INNODB');

    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("emu", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("funnel web", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("lizard", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("dingo", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("kangaroo", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("wallaby", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("wombat", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("koala", "bruce")');
    $db->exec('INSERT INTO animals (animal_type, animal_name) VALUES ("kiwi", "bruce")');

    $db->commit();

    echo 'Table re-created and data entered successfully.';
}
catch(PDOException $e)
{
    $db->rollback();

    echo $e->getMessage();
}

It runs great and like I thought it would, except if I put in an error somewhere. Like if I created a mistake in the fourth insert statement, I would find three animals in my database. But I thought things were supposed to be rolled back, meaning that I would find the database like it was before I ran this script.

Have I misunderstood something? What am I missing? Does the transaction and rollback functions do something else than what I think they should be doing? Is the drop and create statements "breaking" the transaction somehow? What's going on here?


Update: If I move the $db->beginTransaction(); line so the transaction begin only after the table has been created, I get the behavior that I was expecting. So if the third insert statement then failed, I would have an empty table (since it was just recreated) after the transaction was rolled back. Still wondering why it's not working when the drop and create statements are in the transaction though...

+2  A: 

Check the PHP reference manual: PDO::beginTransaction

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

This explains why this happens, and it's a limitation of MySQL, not of PDO/PHP.

wimvds
Ahaaa. That makes sense! Thank you :)
Svish