How can one retrieve the ID of the last inserted record in PHP?
To retrieve the ID of the last inserted record in PHP, you can use the mysqli_insert_id() function which returns the auto-generated ID used in the last query. This function should be called immediately after the INSERT query to ensure you get the correct ID.
// Perform the INSERT query
mysqli_query($connection, "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
// Get the ID of the last inserted record
$last_insert_id = mysqli_insert_id($connection);
echo "The ID of the last inserted record is: " . $last_insert_id;
Related Questions
- Are there any best practices for handling directory structures in PHP to avoid infinite loops?
- What is the difference between using preg_replace and rtrim to remove numbers from the end of a string in PHP?
- In what scenarios would it be more beneficial to handle JSON data directly with JavaScript instead of converting it in PHP before displaying it in an HTML table?