PHP MySQL 上次插入的 ID

在本教程中,你将学习如何使用 PHP 从 MySQL 数据库表中检索最后插入行的唯一 ID。

如何获取上次插入行的 ID

PHP MySQL 插入 章节中,你已经学习了 MySQL 每次在表中插入新记录或行时都会自动为 AUTO_INCREMENT 列生成唯一 ID。但是,在某些情况下,你需要自动生成的 ID 才能将其插入第二个表中。在这些情况下,你可以使用 PHP mysqli_insert_id() 函数来检索最近生成的 ID,如下一个示例所示。

对于此示例,我们将使用我们在 PHP MySQL 创建表 章节中创建的相同 persons 表,其中包含四列 *id*,*first_name*,last_name 和 *email*,其中 id 是主键列并标记为 AUTO_INCREMENT flag。

面向过程式

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', 'ronweasley@mail.com')";
if(mysqli_query($link, $sql)){
    // Obtain last inserted id
    $last_id = mysqli_insert_id($link);
    echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// Close connection
mysqli_close($link);
?>

面向对象式

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "demo");
 
// Check connection
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}
 
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', 'ronweasley@mail.com')";
if($mysqli->query($sql) === true){
    // Obtain last inserted id
    $last_id = $mysqli->insert_id;
    echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} else{
    echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
 
// Close connection
$mysqli->close();
?>

PDO 式

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
    $pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
 
// Attempt insert query execution
try{
    $sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', 'ronweasley@mail.com')";    
    $pdo->exec($sql);
    $last_id = $pdo->lastInsertId();
    echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} catch(PDOException $e){
    die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
 
// Close connection
unset($pdo);
?>