[英]How to get the last inserted id on a table to use it on another insert on another table?
Im trying to get id of the last inserted id on a table called authors
to use it in another insert to a table called mail
. 我试图获取名为
authors
的表上最后插入的id的id,以便在另一个名为mail
的表的插入中使用它。
As you can see this is inserting a new author in table authors
, and right after the insertion it must insert a welcome message to the new author in table mail
. 如您所见,这是在表
authors
插入新authors
,并且插入后必须在表mail
向新作者插入欢迎消息。
Im using mysql_insert_id()
but its not working. 我正在使用
mysql_insert_id()
但无法正常工作。 Nothing is saved to database and no errors occurs. 什么都不会保存到数据库,也不会发生错误。
I know i should not use mysql_query but its ok, thats not the point here, just ignore this please. 我知道我不应该使用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);
}
Why nothing happens when a new author is inserted? 为什么插入新作者后什么也没发生?
Thank you. 谢谢。
您需要将其串联在字符串中,
$sqlmsg = "INSERT INTO mail VALUES (NULL, 1, " . mysql_insert_id() . ", 'Welcome', Hello! Welcome to the website!', 'unread', NOW, 0, 0)";
Try saving it on a temporary variable before using it on the next query. 尝试将其保存在一个临时变量上,然后在下一个查询中使用它。
<?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);
}
?>
Use a select query on the table and order by 'id' desc with limit 1 在表上使用选择查询,并按'id'desc进行排序(限制为1)
select `id` from `authors` order by `id desc limit 1
will return the last id if it's auto incremented. 如果自动递增,将返回最后一个ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.