mysqli_rollback($con) is not working

2019-09-16 12:18发布

问题:

<?php

$serverName = "localhost";
$username = "root";
$password = "";
$Database = "database";
$con = mysqli_connect($serverName, $username, $password, $Database);
if (mysqli_connect_errno()) {
    echo "PLEASE IMPORT THE DATABASE";
}

try {
    mysqli_autocommit($con,FALSE);
    for ($i=1; $i < 100; $i++) { 
        $Query = "INSERT INTO `test`(`id`, `name`, `version`) VALUES ('".$i."','name".$i."','version".$i."')";
        $Result = mysqli_query($con,$Query);
        if($Result==false){
            throw new Exception(" Error Found at index " . $i);
        }
    }
    echo "calling commit";
    mysqli_commit($con);
}
catch(Exception $e) {
    echo "calling rollback";
    mysqli_rollback($con);
    echo 'Message: ' .$e->getMessage();
}

I have created a test file for testing rollback(). In test table id as primary key.

First time i executed this file, so 99 records(id from 1 to 99) is inserted.

result : 
calling commit

Now i removed pk value 1,2,3 from test table. Now the table has 96 records(id from 4 to 99) if i run the file aging

result : 
calling rollbackMessage: Error Found at index 4

But the pk value 1,2,3 is stored in the table even i call the rollback(). Now the table has 99 records(id from 1 to 99) Why it is happening? Please help me.

回答1:

Check your Database Storage Engine. If it is MyISAM, change it into InnoDB.



回答2:

I do not know if I understanding very well, but...

  1. If you have a primary key on the table, you do not need the to inform ID field on INSERT.

  2. If you try to run the file by second time, I think that this error occurs because the table already an id 4 and the script try insert again.



标签: php mysqli