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 use a variable in a MySQL query using PHP?
- How to write an update query in MySQL using PHP?
- How to output XML from MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the first row of a result in MySQL using PHP?
- How to update to null value in MySQL using PHP?
- How to generate a UUID in MySQL using PHP?
- How to join tables with PHP and MySQL?
- How to check the result of an insert in PHP and MySQL?
See more codes...