[英]How to get the last inserted id on a table to use it on another insert on another table?
我試圖獲取名為authors
的表上最后插入的id的id,以便在另一個名為mail
的表的插入中使用它。
如您所見,這是在表authors
插入新authors
,並且插入后必須在表mail
向新作者插入歡迎消息。
我正在使用mysql_insert_id()
但無法正常工作。 什么都不會保存到數據庫,也不會發生錯誤。
我知道我不應該使用mysql_query,但是還可以,這不是重點,請忽略此內容。
if(!isset($row[email])){
$sql = "INSERT INTO authors VALUES (NULL, 0, '".$email."', '".$username."', NULL, '".$first."', '".$fullname."', '".$first."', NULL, NULL, NULL, NULL,'http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."', 0);";
mysql_query($sql);
$sqlmsg = "INSERT INTO mail VALUES (NULL, 1, mysql_insert_id(), 'Welcome', Hello! Welcome to the website!', 'unread', NOW, 0, 0)";
mysql_query($sqlmsg);
}
為什么插入新作者后什么也沒發生?
謝謝。
您需要將其串聯在字符串中,
$sqlmsg = "INSERT INTO mail VALUES (NULL, 1, " . mysql_insert_id() . ", 'Welcome', Hello! Welcome to the website!', 'unread', NOW, 0, 0)";
嘗試將其保存在一個臨時變量上,然后在下一個查詢中使用它。
<?php
if(!isset($row[email])){
$sql = "INSERT INTO authors VALUES (NULL, 0, '".$email."', '".$username."', NULL, '".$first."', '".$fullname."', '".$first."', NULL, NULL, NULL, NULL,'http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."', 0);";
mysql_query($sql);
$author_id = mysql_insert_id();
$sqlmsg = "INSERT INTO mail VALUES (NULL, 1, $author_id, 'Welcome', Hello! Welcome to the website!', 'unread', NOW, 0, 0)";
mysql_query($sqlmsg);
}
?>
在表上使用選擇查詢,並按'id'desc進行排序(限制為1)
select `id` from `authors` order by `id desc limit 1
如果自動遞增,將返回最后一個ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.