How can one optimize PHP scripts that involve multiple database inserts to improve performance?

To optimize PHP scripts that involve multiple database inserts, you can use transactions to group the inserts together and reduce the number of round trips to the database. This can improve performance by ensuring that all inserts are either committed or rolled back together, reducing the overhead of multiple individual transactions.

// Start a transaction
$pdo->beginTransaction();

// Perform multiple database inserts
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);

$value1 = 'example1';
$value2 = 'example2';
$stmt->execute();

$value1 = 'example3';
$value2 = 'example4';
$stmt->execute();

// Commit the transaction
$pdo->commit();