mysqli::$insert_id
(mysqli_insert_id) Returns the automatically generated id used in the latest query
The mysqli_insert_id() function returns the id generated by the last query (generated using AUTO_INCREMENT).
Suppose the "Persons" table has an automatically generated id field. Return the id of the last query:
<?php
$mysqli = new mysqli ( "localhost" , "my_user" , "my_password" , "my_db" ) ;
if ( $mysqli -> connect_errno ) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error ;
exit ( ) ;
}
$mysqli -> query ( "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)" ) ;
// Print the automatically generated id
echo "New record has id: " . $mysqli -> insert_id ;
$mysqli -> close ( ) ;
?>
Suppose the "Persons" table has an automatically generated id field. Return the id of the last query:
<?php
$con = mysqli_connect ( "localhost" , "my_user" , "my_password" , "my_db" ) ;
if ( mysqli_connect_errno ( ) ) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ( ) ;
exit ( ) ;
}
mysqli_query ( $con , "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)" ) ;
// Print the automatically generated id
echo "New record has id: " . mysqli_insert_id ( $con ) ;
mysqli_close ( $con ) ;
?>