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

2022-08-30 19:40:13

我有以下代码。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);
}

答案 1

mysqli_insert_id返回表最后一行的 ID。从文档中,它:

...返回由对具有 AUTO_INCREMENT 属性的列的表的查询生成的 ID。如果最后一个查询不是 or 语句,或者修改后的表没有包含该属性的列,则此函数将返回零INSERTUPDATEAUTO_INCREMENT

(我的强调)

也就是说,如果要在自动生成 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);

答案 2

要获得结果,您应该将

$last_row = mysqli_insert_id($connection);

在插入查询之后


推荐