PHP mysqli_insert_id() 函数


实例

假设 Persons 表有一个自动生成的 ID 字段。返回最后一次查询中的 ID:

  1. <?php
    $con=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno($con))
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
    VALUES ('Glenn','Quagmire',33)");

    // Print auto-generated id
    echo "New record has id: " . mysqli_insert_id($con);

    mysqli_close($con);
    ?>

定义和用法

mysqli_insert_id() 函数返回最后一个查询中自动生成的 ID(通过 AUTO_INCREMENT 生成)。

语法

  1. mysqli_insert_id(connection);

参数 描述
connection 必需。规定要使用的 MySQL 连接。

技术细节

返回值: 返回一个在最后一个查询中自动生成的带有 AUTO_INCREMENT 字段值的整数。如果数字 > 最大整数值,它将返回一个字符串。如果没有更新或没有 AUTO_INCREMENT 字段,将返回 0。
PHP 版本: 5+