简体   繁体   English

PHP事务没有回滚

[英]PHP transaction not rolling back

I have some PHP code that reads a spreadsheet using PHPExcel and imports the data into a MySQL database. 我有一些PHP代码使用PHPExcel读取电子表格并将数据导入MySQL数据库。 (innoDB) If the import encounters a duplicate record in the database it's supposed to fail and rollback all prior inserts. (innoDB)如果导入在数据库中遇到重复记录,则应该失败并回滚所有先前的插入。 The rollback is not working, I wrote this small program that functions the same way. 回滚不起作用,我编写了这个以相同方式运行的小程序。

$conn = null;
try {

$conn=new mysqli("myServer","user","password", "moveforward");
$conn->autocommit(FALSE);

$sql="insert into series (seriesLocation,seriesName,seriesDate) values('1','2','2013-05-21')";
echo "Executing query 1<br>";
$conn->query($sql);
if($conn->error!="") {
    $sqlError=$conn->error;
    $conn->rollback();
    echo "Rollback complete<br>";
    throw new Exception($sqlError);
}

//This will throw a duplicate exception
echo "Exceuting query 2<br>";
$conn->query($sql);
if($conn->error!="") { 
    $sqlError=$conn->error;
    $conn->rollback();
    echo "Rollback complete<br>";
    throw new Exception($sqlError);
}
echo "You shouldn't be here<br>";

$conn->commit();
echo "Transactions comitted<br>";

} catch (Exception $e) {
    echo "Exception: " . $e->getMessage() . "<br>";
}
$conn->close();
echo "Done<br>";

In looking at the php manual and checking other posts on here this looks like it should work. 在查看php手册并查看此处的其他帖子时,看起来它应该可以正常工作。 When I run it I get this: 当我运行它时,我得到了这个:

Executing query 1
Exceuting query 2
Rollback complete
Exception: Duplicate entry '2' for key 'seriesName'
Done

Yet when I check the database the data from the first insert is in there. 然而,当我检查数据库时,第一个插入的数据就在那里。

Any ideas? 有任何想法吗?

Guess your tables doesn't use an appropriate engine 猜猜你的桌子没有使用合适的引擎

http://php.net/mysqli.autocommit http://php.net/mysqli.autocommit

This function doesn't work with non transactional table types (like MyISAM or ISAM). 此函数不适用于非事务表类型(如MyISAM或ISAM)。

However, it is much easier to use INSERT IGNORE (or REPLACE depending on what should be the correct behaviour) instead. 但是,使用INSERT IGNORE (或REPLACE取决于应该是正确的行为)更容易。 In this case the duplicated rows are silently ignored (or replace the existing one ( REPLACE )). 在这种情况下,将以静默方式忽略重复的行(或替换现有的行( REPLACE ))。 Of course this doesn't work, if you want to know, which are the duplicates. 当然,如果您想知道哪些是重复的,这是行不通的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM