PHP PDO Creating Multiple Tables in a Transaction

I have the following bit of PHP code that creates three database tables and then tries to cancel a transaction.

$dbh = new \PDO("mysql:host=localhost;dbname=dbname", 'usernamehere', 'passwordhere');
$dbh->setAttribute(\PDO::ATTR_AUTOCOMMIT,FALSE);
$dbh->beginTransaction();
$sql = "CREATE TABLE IF NOT EXISTS `a` (`id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$dbh->exec($sql);
$sql = "CREATE TABLE IF NOT EXISTS `b` (`id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$dbh->exec($sql);
$sql = "CREATE TABLE IF NOT EXISTS `c` (`id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$dbh->exec($sql);
$dbh->rollBack();

I expect the tables will not be created, but they are. Any thoughts?

+5
source share
1 answer

The user manual answers this question.

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 in a transaction. Implicit COMMIT will not allow you to roll back any other changes at the transaction boundary.

+9
source

All Articles