What is the best way to retrieve the ID of a newly inserted record in a MySQL database using PHP?
When inserting a new record into a MySQL database using PHP, the best way to retrieve the ID of the newly inserted record is by using the mysqli_insert_id() function. This function returns the auto-generated ID used in the last query. After inserting the record, call mysqli_insert_id() to get the ID value.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Insert a new record
$mysqli->query("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
// Get the ID of the newly inserted record
$new_id = $mysqli->insert_id;
// Use the ID as needed
echo "The ID of the newly inserted record is: " . $new_id;
Related Questions
- How can hosting providers assist in resolving PHP database connection issues, particularly related to user permissions and password authentication?
- What is the best way to create a drop-down menu in PHP that displays or hides text based on user selection?
- What are the limitations of using PHP to check if a specific process is running on a server?