What is the best way to retrieve the auto-incremented ID value after inserting a record into a MySQL database using PHP?
After inserting a record into a MySQL database using PHP, the best way to retrieve the auto-incremented ID value is by using the mysqli_insert_id() function provided by PHP. This function returns the ID generated by the most recent INSERT query. You can store this value in a variable for further use in your code.
// Insert record into database
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
$result = mysqli_query($connection, $query);
// Retrieve auto-incremented ID
$last_id = mysqli_insert_id($connection);
// Make use of the $last_id as needed
echo "The auto-incremented ID is: " . $last_id;
Keywords
Related Questions
- What are some best practices for creating a download area with subfolders using PHP and JavaScript?
- What best practices should be followed when designing a guestbook system in PHP to ensure data integrity and security?
- What steps can be taken to optimize a PHP script that is experiencing issues with displaying content in the browser while still processing data in the background?