2013-03-11 144 views
8

我有以下代碼。應該返回表的最後一行的mysqli_insert_id()(在本例中爲「$ last_row」)總是返回0.爲什麼這樣呢?爲什麼mysqli_insert_id()總是返回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); 
} 

?> 
+1

「*返回值:AUTO_INCREMENT字段的值這由前面的查詢更新**如果在連接上沒有以前的查詢,或者查詢沒有更新AUTO_INCREMENT值,則返回零**。*「 – DCoder 2013-03-11 06:14:13

+0

Look:http://php.net/manual/en /mysqli.insert-id.php – 2015-02-12 01:08:49

回答

16

mysqli_insert_id返回表的最後一排的ID。從the docs開始,它:

...返回由具有AUTO_INCREMENT屬性的列的表上的查詢生成的ID。如果最後一個查詢不是INSERTUPDATE語句,或者如果修改後的表沒有包含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); 
11

要得到的結果,您應該在INSERT查詢

+1

在mysqli_insert_id()中指定$連接很重要。否則,ID不能被檢索。 – Devner 2016-02-11 07:44:13

0

對於其他人後放置

$last_row = mysqli_insert_id($connection); 

來到這裏,也許你試過了INSERT IGNORE INTO,並且你已經插入了一個UNIQUE值。在這種情況下,這個ID是零。

如果MySQL沒有連接,你也會得到「零」。我不是持久連接的專家,但這可能有助於某人?

正如你可能知道PHP「MySQL的」擴展支持持續 連接,但他們在新的「mysqli的」擴展名被禁用 --Peter採夫