Hướng dẫn last insert id mysql
Get ID of The Last Inserted RecordIf we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately. Show In the table "MyGuests", the "id" column is an AUTO_INCREMENT field: CREATE TABLE MyGuests ( The following examples are equal to the examples from the previous page (PHP Insert Data Into MySQL), except that we have added one single line of code to retrieve the ID of the last inserted record. We also echo the last inserted ID: Example (MySQLi Object-oriented)$servername = "localhost"; // Create connection $sql = "INSERT INTO MyGuests (firstname, lastname, email) if ($conn->query($sql) === TRUE) { $conn->close(); Example (MySQLi Procedural)$servername = "localhost"; // Create connection $sql = "INSERT INTO MyGuests (firstname, lastname, email) if (mysqli_query($conn, $sql)) { mysqli_close($conn); Example (PDO)$servername = "localhost"; try { $conn = null; (PHP 4, PHP 5) mysql_insert_id — Get the ID generated in the last query Descriptionmysql_insert_id(resource Parameterslink_identifier The
MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an Return Values The ID generated for an AUTO_INCREMENT column by the previous query on success, ExamplesExample #1 mysql_insert_id() example
NotesCaution mysql_insert_id() will convert the return type of the native MySQL C API function
See Also
Alfred Nony Mouse ¶ 14 years ago
bargainbatman at gmail dot com ¶ 12 years ago
?> foros (_AT_) anthalia.com ¶ 15 years ago
elinor dot hurst at REMOVETHIS dot gmail dot com ¶ 14 years ago
Anonymous ¶ 16 years ago
hoangvu4000 at gmail dot com ¶ 9 years ago
dhiraj dot webdeveloper at gmail dot com ¶ 4 years ago
mysqli_query($conn, $sql)) { vksgeneric at hotmail dot com ¶ 22 years ago
heiligkind at yahoo dot de ¶ 16 years ago
louis at intoplay dot com ¶ 15 years ago
Steve Bond ¶ 18 years ago
|