如何在没有第二个查询的情况下获取最后一个Insert语句的结果的id?
我知道我可以选择数据库的最后一行来获取我正在寻找的东西......有时候。问题是如果两个用户同时插入,我担心他们可能会得到错误的结果。
伪示例代码:
User 1 - Insert Record A
User 1 - Select last Record
User 1 - Record A Selected
伪多用户问题:
User 1 - Insert Record A
User 2 - Insert Record B
User 1 - Select last Record
**User 1 - Record B Selected**
User 2 - Select last Record
User 2 - Record B Selected
答案 0 :(得分:2)
您可以使用mysql_insert_id()
或mysqli_insert_id
来获取最后插入的ID
答案 1 :(得分:1)
当用户使用不同的连接时,不会发生此问题。在不同的请求中应始终如此。但即使在同一个脚本中,使用不同的连接也可以确保分离。
证明:
$connection_for_user1 = new MySQLi('localhost', 'user', 'pass', 'test');
$connection_for_user2 = new MySQLi('localhost', 'user', 'pass', 'test');
$result_for_user1 = $connection_for_user1->query("INSERT INTO test_table (data) VALUES ('A')");
$result_for_user2 = $connection_for_user2->query("INSERT INTO test_table (data) VALUES ('B')");
$record_id_for_user1 = $connection_for_user1->insert_id;
$record_id_for_user2 = $connection_for_user2->insert_id;
echo "User 1: record $record_id_for_user1\n";
echo "User 2: record $record_id_for_user2\n";
结果:
User 1: record 1
User 2: record 2