grep
grep

Reputation: 4016

PHP PDO transaction issues

I have a simple try catch which is not operating how I would expect. This is my first try at using transactions with PDO:

try
        {
            $dbo = Db::init();
            $dbo->beginTransaction();
            $dbo->exec("TRUNCATE TABLE {$this->table}");
            $dbo->exec($insert);
            $dbo->commit();
        }
        catch(Exception $e)
        {
            $dbo->rollBack();
            echo 'Failed to sync ' . $this->table; 
        }

The problem is, if the $dbo->exec($insert); fails, the $dbo->exec("TRUNCATE TABLE {$this->table}"); does not get rolled back. Any ideas?

Upvotes: 5

Views: 1920

Answers (2)

dbellizzi
dbellizzi

Reputation: 713

Assuming you're using MySQL, TRUNCATE TABLE has an implicit COMMIT. From the documentation at http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html :

As of MySQL 5.0.8, truncate operations cause an implicit commit. Before 5.0.8, truncate operations are not transaction-safe; an error occurs when attempting one in the course of an active transaction. 

Upvotes: 4

zerkms
zerkms

Reputation: 254886

TRUNCATE cannot be rolled back. Use DELETE instead.

Upvotes: 6

Related Questions