What is the recommended method for retrieving the last inserted ID in a MySQL database using PHP?
When inserting a new record into a MySQL database using PHP, you may want to retrieve the auto-generated ID of the last inserted record for further processing or referencing. One common method to achieve this is by using the mysqli_insert_id() function in PHP, which returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
// Connect to MySQL database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Insert a new record into the database
mysqli_query($conn, "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
// Get the ID of the last inserted record
$last_id = mysqli_insert_id($conn);
// Output the last inserted ID
echo "Last inserted ID: " . $last_id;
// Close the database connection
mysqli_close($conn);
Keywords
Related Questions
- How can the selected value in a dropdown field be displayed at the top of the list after the page reloads in PHP?
- Where can comprehensive resources or tutorials be found to better understand the relationships between various HTTP classes in PHP and how to use them effectively in web development projects?
- What is the correct syntax for the WHERE clause in the SQL query to filter data based on a date difference in PHP?