简体   繁体   中英

PHP/mysqli: unintended rollback in query across two mysql databases

I am trying to restore some data from a backup database. All tables are Innodb, I am using PHP/mysqli for scripting. I am trying with or without a transaction, but that makes no difference.

So I open a DB connection as user "root" and do:

INSERT INTO maindb.table1 SELECT * FROM backupdb.table1 WHERE user_id = 1234;

Afterwards, affected_rows returns 825 rows, as it should be. There does not appear to be an error anywhere. An immediate

SELECT COUNT(*) FROM table1 WHERE user_id = 1234

shows 825 rows.

However, upon the script exiting, the row count in table1 for user_id 1234 is again 0.

It appears that there is an automatic rollback at the end, but I cannot for the life of me understand why. Maybe it is because there are two databases involved? I have never heard of such a behavior before.

When I run the same query on the mysql command line as root, the rows are properly inserted, and the row count afterwards is 825.

Here is my example code:

$db = new mysqli(
    'localhost',
    'root',
    $password,
    'maindb'
);

$uid = 1234;

//$db->begin_transaction();
$db->query("INSERT INTO maindb.table1 SELECT * FROM backupdb.table1 WHERE user_id = $uid");
echo "table1: " . $db->affected_rows . "\n";
$st = $db->query("SELECT count(*) FROM maindb.table1 WHERE user_id = $uid");
var_dump($st->fetch_all());
//$db->commit();

$db->close();

Result:

table1: 825
array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(3) "825"
  }
}

Any ideas why the rollback is happening and how to avoid it?

Oops. Found it, here is the culprit:

REPLACE INTO maindb.user SELECT * FROM backupdb.user WHERE id =  $uid

This was at the end of the script, I had omitted that. What mysql REPLACE does is delete the user (including all dependent data in other tables -> ON DELETE CASCADE) and insert the row anew. That means that all of the data previously copied is deleted. Sorry for the confusion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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