从mysql中的INSERT查询返回一个值?

时间:2012-07-11 23:16:31

标签: php mysql insert

  

可能重复:
  PHP: how to get last inserted ID of a table?

这是我在posts表(PHP / mysql)中插入新帖子的查询。我可以为刚刚插入同一语句的帖子返回post_id吗?我需要将post_id插入到另一个表中。

mysql_query("INSERT INTO `posts` (`post_id`, `date`, `title`, `content`) VALUES (NULL,    NOW(), '$title', '$fileName')");

3 个答案:

答案 0 :(得分:0)

mysql_insert_id()将为您提供最后一个ID

答案 1 :(得分:0)

这正是MySQL函数last_insert_id()的用途。所以,基本上答案是,“不,但有点”。您需要执行一个额外的查询“select last_insert_id()”,它将返回1行,其中包含您的ID。

答案 2 :(得分:0)

mysql_query("INSERT INTO `posts` (`date`, `title`, `content`) VALUES (NOW(), '$title', '$fileName')");
$last_inserted = mysql_insert_id(); // return last inserted id