What is the purpose of using mysql_insert_id() function in PHP?
The mysql_insert_id() function in PHP is used to retrieve the ID generated by a query (usually an INSERT query) on a table with an AUTO_INCREMENT column. This function is useful when you need to get the ID of the last inserted record in order to perform further operations or to display it to the user.
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Perform an INSERT query
$query = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
mysqli_query($connection, $query);
// Get the ID of the last inserted record
$last_insert_id = mysqli_insert_id($connection);
// Use the ID for further operations
echo "The ID of the last inserted record is: " . $last_insert_id;
Related Questions
- How can the HTTP wrapper error related to writeable connections be resolved in PHP when uploading images?
- In the provided PHP code snippet, what improvements or changes can be made to the header settings to troubleshoot the issue of the download dialog not opening?
- In what scenarios would it be more efficient to have multiple users share a single database record in PHP?