What are the best practices for storing data from a loop in a database in PHP, especially when the data needs to be saved after multiple iterations of the loop?

When storing data from a loop in a database in PHP, especially when the data needs to be saved after multiple iterations of the loop, it is best practice to use prepared statements to prevent SQL injection and improve performance. Additionally, you can use transactions to ensure atomicity and consistency when saving data in bulk.

// Assuming you have established a database connection

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

// Prepare a statement for insertion
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");

foreach ($data as $item) {
    // Bind parameters and execute the statement
    $stmt->bindParam(':value1', $item['value1']);
    $stmt->bindParam(':value2', $item['value2']);
    $stmt->execute();
}

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