0

如何在没有第二次查询的情况下获取最后一个 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
4

2 回答 2

2

您可以使用mysql_insert_id()mysqli_insert_id获取最后插入的 id

于 2013-05-26T23:30:41.853 回答
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
于 2013-05-28T12:12:39.577 回答