How can one optimize the insertion of multiple records into a table in PHP?
When inserting multiple records into a table in PHP, it is more efficient to use prepared statements and execute them in a loop rather than executing individual queries for each record. This helps reduce the number of database calls and improves performance.
// Sample code to optimize insertion of multiple records into a table in PHP
// Assuming $records is an array of records to be inserted
$records = [
['John', 'Doe'],
['Jane', 'Smith'],
['Alice', 'Johnson']
];
// Prepare the SQL statement
$sql = "INSERT INTO users (first_name, last_name) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
// Loop through each record and execute the prepared statement
foreach ($records as $record) {
$stmt->execute($record);
}