【问题标题】:Return a value from an INSERT query in mysql? [duplicate]从 mysql 中的 INSERT 查询返回一个值? [复制]
【发布时间】:2012-07-11 16:15:30
【问题描述】:

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

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

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

【问题讨论】:

  • @Michael 在第一条评论中输入错误mysql_insert_id() 或SELECT LAST_INSERT_ID()

标签: php mysql insert


【解决方案1】:
mysql_query("INSERT INTO `posts` (`date`, `title`, `content`) VALUES (NOW(), '$title', '$fileName')");
$last_inserted = mysql_insert_id(); // return last inserted id

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      mysql_insert_id()会给你最后一个ID

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-25
        • 2010-11-21
        • 1970-01-01
        • 2013-09-27
        相关资源
        最近更新 更多