How can the mysql_insert_id() function be used to retrieve the auto_increment ID after inserting a record in PHP?
When inserting a record into a MySQL database table with an auto_increment primary key column, you can use the mysql_insert_id() function in PHP to retrieve the last inserted ID. This function returns the ID generated by the most recent INSERT query, which is useful for getting the auto_increment ID of the record just inserted. You can then use this ID for further operations or to display to the user.
// Insert a record into the database
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
$result = mysqli_query($connection, $query);
// Get the auto_increment ID of the inserted record
$last_insert_id = mysqli_insert_id($connection);
// Use the ID for further operations
echo "The ID of the inserted record is: " . $last_insert_id;
Related Questions
- What other PHP functions can be used in conjunction with fgetcsv() to process CSV data efficiently?
- How can the issue of the first value being ignored in the output be resolved in the provided script?
- In what ways can PHP developers optimize their code for efficient data retrieval and manipulation in scenarios involving user registration and account creation processes?