簡體   English   中英

PHP檢索插入的最后一條記錄的ID,並將其插入另一個表

[英]php retrieving id of the last record inserted and insert it in another table

我正在嘗試檢索表'authors'中插入的最后一條記錄的ID,並將檢索到的ID插入'articles'表中; 這是我的代碼:

$title = mysql_real_escape_string($_POST[title]);
$body = mysql_real_escape_string($_POST[body]);
$category = mysql_real_escape_string($_POST[category]);

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
$select_author= mysql_query("SELECT LAST_INSERT_ID()");

$authId = mysql_fetch_array($select_author);
$query="INSERT INTO articles (body, date, category, auth_id) VALUES ('$body', '$date_now', '$category', '$authId')";

這不起作用...

有什么想法嗎?

提前致謝

毛羅

您可以使用mysql_insert_id()獲得最后的插入ID

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
mysql_query($insert_author) or die(mysql_error());

$authId = mysql_insert_id();

$query="INSERT INTO articles (body, date, category, auth_id) VALUES
('$body', '$date_now', '$category', '$authId')";

請注意 ,您缺少用於插入查詢的mysql_query函數,我也在上面的代碼中添加了該函數。

到底什么不起作用。 $authId包含期望值? 你把它扔了檢查嗎?

除此之外,您忘記了第二個mysql_query()

請嘗試使用mysql-insert-id

顧名思義, mysql_fetch_array($select_author)返回一個數組,因此您將需要獲取該數組中的特定值以插入另一個表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM