PHP MySQL 获取最后插入 ID
获取最后插入记录的 ID
如果我们对具有 AUTO_INCREMENT 字段的表执行 INSERT 或 UPDATE 操作,我们可以立即获取最后插入/更新记录的 ID。
在 "MyGuests" 表中,"id" 列是 AUTO_INCREMENT 字段
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
以下示例与上一页的示例相同 (PHP 将数据插入 MySQL),只是我们在代码中添加了一行代码来检索最后插入记录的 ID。我们还将最后插入的 ID 输出。
示例 (MySQLi 面向对象)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 建立连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "新记录创建成功。最后插入的 ID 为: " . $last_id;
} else {
echo "错误: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
示例 (MySQLi 过程化)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 建立连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "新记录创建成功。最后插入的 ID 为: " . $last_id;
} else {
echo "错误: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
示例 (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 将 PDO 错误模式设置为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
// 使用 exec() 因为没有结果返回
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "新记录创建成功。最后插入的 ID 为: " . $last_id;
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>