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);
Related Questions
- How can parameters be passed in a URL beyond the question mark when using the "get" method in PHP forms?
- How can PHP developers ensure consistent data formatting for addresses, such as standardizing street names and abbreviations, while allowing for variations in user input?
- What is the recommended method to add content to the beginning of a .txt file in PHP while preserving the existing content?