【问题标题】:How to get the value of id(primary key) in previous operation in MySQL如何在 MySQL 中获取先前操作中 id(primary key) 的值
【发布时间】:2009-12-02 06:26:52
【问题描述】:

我正在使用 MySQL。我需要先在表中插入一行,然后我需要获取插入行的 id。代码如下所示:

insert into mytable (column2, column3, column4) values('value2','value3','value4')or die(mysql_error());

第 1 列

主键

它是自动递增的。那么如何获取

的值

第 1 列

在之前的操作中?

【问题讨论】:

    标签: php mysql database insert lastinsertid


    【解决方案1】:

    您可以使用mysql_insert_id。来自文档:

    <?php
    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('mydb');
    
    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    printf("Last inserted record has id %d\n", mysql_insert_id());
    ?>
    

    【讨论】:

      【解决方案2】:

      您可能正在寻找mysql_insert_id 函数:

      检索为一个生成的 ID AUTO_INCREMENT 上一栏 查询(通常是 INSERT)。

      mysqli_insert_idPDO::lastInsertId,取决于您用于访问 MySQL 数据库的扩展。

      【讨论】:

        猜你喜欢
        • 2017-07-24
        • 2011-04-20
        • 1970-01-01
        • 2020-10-26
        • 2013-06-25
        • 2016-11-12
        • 2021-10-18
        • 2019-09-30
        相关资源
        最近更新 更多