php-mysqlHow to get the last insert ID in PHP MySQL?
The last insert ID in PHP MySQL can be obtained using the mysqli_insert_id()
function. This function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
Example code
$conn = mysqli_connect("localhost", "username", "password", "database");
$sql = "INSERT INTO table (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
$result = mysqli_query($conn, $sql);
$last_id = mysqli_insert_id($conn);
echo "Last insert ID is: " . $last_id;
Output example
Last insert ID is: 5
Code explanation
mysqli_connect()
: Establishes a connection to a MySQL server.mysqli_query()
: Executes a query against the database.mysqli_insert_id()
: Returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
Helpful links
More of Php Mysql
- How to create an SSL connection to MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to return multiple rows as an array in MySQL using PHP?
- How to get the error message for a MySQL query using PHP?
- How to run multiple queries in PHP and MySQL?
- How to prepare a statement in MySQL using PHP?
- How to join tables with PHP and MySQL?
- How to update to null value in MySQL using PHP?
- How to replace a string in MySQL using PHP?
- How to escape JSON in PHP and MySQL?
See more codes...