gpt4 book ai didi

php - 为什么 mysqli_insert_id() 总是返回 0?

转载 作者:行者123 更新时间:2023-11-30 21:56:45 25 4
gpt4 key购买 nike

我有以下代码。应该返回表的最后一行的 mysqli_insert_id()(在本例中为“$last_row”)始终返回 0。为什么会这样?

<?php

include 'connect-db.php';
$last_row = mysqli_insert_id($connection);

if ($content != '') {
$sql = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";

if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}

echo $last_row;
mysqli_close($connection);
}

最佳答案

mysqli_insert_id 返回表最后一行的 ID。来自 the docs ,它:

...returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

(我的重点)

也就是说,如果您要在自动生成 ID 的插入操作之后立即运行它,在您执行插入操作的同一连接上,它将返回为该插入操作生成的 ID。

上面链接的文档中的示例说明了这一点:

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

关于php - 为什么 mysqli_insert_id() 总是返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44903494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com