Cách lấy ID được thêm cuối cùng trong bảng MySQL

Trong bài hướng dẫn này, chúng ta sẽ học cách truy xuất ID duy nhất của hàng được thêm vào cuối cùng từ bảng cơ sở dữ liệu MySQL bằng PHP.

Cách lấy ID của hàng được thêm vào cuối cùng

Trong bài Thêm dữ liệu vào bảng mà bạn đã học MySQL tự động tạo một ID duy nhất (AUTO_INCREMENT) cho cột ID mỗi khi bạn chèn một bản ghi hoặc hàng mới vào bảng. Tuy nhiên, có một số tình huống khi bạn cần ID được tạo tự động đó để chèn nó vào bảng thứ hai. Trong những trường hợp này, bạn có thể sử dụng hàm  mysqli_insert_id() để truy xuất ID được tạo gần đây nhất, như được hiển thị trong ví dụ dưới đây.

Đối với ví dụ này, chúng ta sẽ sử dụng cùng một bảng persons mà chúng tôi đã tạo trong chương Tạo bảng, có bốn cột id, first_name, last_name và email trong đó id là cột khóa chính và được đánh dấu bằng AUTO_INCREMENT.

Thủ tục

<?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);
?>

Hướng đối tượng

<?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);
?>

 

Bài viết mới cập nhật