How can the LAST_INSERT_ID() function be utilized in PHP to improve database operations when storing survey data?

When storing survey data in a database, it is important to keep track of the last inserted ID to ensure data integrity and avoid errors. The LAST_INSERT_ID() function in MySQL can be utilized in PHP to retrieve the ID of the last inserted record, which can then be used to link related data in other tables or for further processing.

// Insert survey data into the database
$query = "INSERT INTO surveys (question, answer) VALUES ('What is your favorite color?', 'Blue')";
$result = mysqli_query($connection, $query);

// Get the ID of the last inserted record
$last_insert_id = mysqli_insert_id($connection);

// Use the last inserted ID for further operations
$query2 = "INSERT INTO survey_responses (survey_id, response) VALUES ($last_insert_id, 'Blue is my favorite color')";
$result2 = mysqli_query($connection, $query2);