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

Mum*_*mbo 14 php mysql

我有以下代码.mysqli_insert_id()(在本例中为"$ last_row"),应该返回表的最后一行,总是返回0.为什么会这样?

<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysqli_real_escape_string($connection, htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
$last_row = mysqli_insert_id($connection);

if ($content != '') {

$sql = "INSERT INTO source ( track_id, submit_date, ip, content) VALUES ('$last_row', '$submit_date','$ip_address','$content')";

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

echo $last_row;
mysqli_close($connection);
}

?>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 21

mysqli_insert_id没有返回表的最后一排的ID.从文档中,它:

...返回由具有AUTO_INCREMENT属性的列的表上的查询生成的ID.如果最后一个查询不是INSERT或者UPDATE语句,或者如果修改后的表没有具有该AUTO_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);
Run Code Online (Sandbox Code Playgroud)


Sud*_*Pal 17

要获得结果,您应该放置

$last_row = mysqli_insert_id($connection);
Run Code Online (Sandbox Code Playgroud)

在INSERT查询之后

  • 在mysqli_insert_id()中指定$ connection非常重要.否则无法检索ID. (2认同)