获取最后插入的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
)
下面的例子是等于从以前的页面(示例PHP将数据插入到MySQL的 ),除了我们已经添加了一行代码来检索最后插入记录的ID。 我们也呼应了最后插入的ID:
实施例(MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password =
"password";
$dbname =
"myDB";
// Create connection
$conn =
new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $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 "New record created successfully. Last
inserted ID is: " . $last_id;
} else {
echo
"Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
实施例(MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password =
"password";
$dbname =
"myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection
failed: " . 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 "New record created
successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: "
. $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);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO
MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
// use exec() because no
results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record
created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>