MySQL Transaction+ PHP issue in Mysql
I have a code which was used in an application 开发者_运维技巧where I am having a problem in rollback. Even if I 's2' returns false rollback isn't happening i.e. table 'products' is getting droped. Can anyone explain why it isn't working or how should I change it. Note: tables are of Innodb engine..I use mysql 5.0+
mysql_query('SET AUTOCOMMIT=0;');
mysql_query('START TRANSACTION;');
$sql = 'DROP TABLE '.$this->Product->tablePrefix.'products';
$s1 = mysql_query($sql);
$sql = 'RENAME TABLE '.$this->Product->tablePrefix.'temp12212 TO '.$this->Product->tablePrefix.'products';
$s2 =mysql_query($sql);
if($s1 && $s2){
mysql_query('COMMIT;');
$this->Session->setFlash('Commit Successful to Database');
}else{
mysql_query('ROLLBACK;');
$this->Session->setFlash('Commit failed due to some errors<br> auto-rollbacked to previous state');
}
DROP TABLE
is one of the commands in MySql that cause a implicit commit.
http://dev.mysql.com/doc/refman/5.1/en/implicit-commit.html
Use this instead:
'RENAME TABLE '.$this->Product->tablePrefix.'products TO backup_table
, '.$this->Product->tablePrefix.'temp12212 TO '.$this->Product->tablePrefix.'products';
You cannot rollback a DROP TABLE
or RENAME TABLE
statement as they cause an implicit commit.
I sorted the problem this way instead!!! thanks all for your reply :-)
$sql = 'DROP TABLE IF EXISTS '.$this->Product->tablePrefix.'temp_backup';
mysql_query($sql);
$sql = 'RENAME TABLE '.$this->Product->tablePrefix.'products TO '.$this->Product->tablePrefix.'temp_backup, '.$this->Product->tablePrefix.'temp TO '.$this->Product->tablePrefix.'products';
$status =mysql_query($sql);
if($status){
$sql = 'DROP TABLE '.$this->Product->tablePrefix.'temp_backup';
mysql_query($sql);
$this->Session->setFlash('Commit Successful to Database');
}else{
$this->Session->setFlash('Commit failed due to some errors<br> auto-rollbacked to previous state');
}
精彩评论