How can the foreach loop be optimized for updating multiple database records based on checkbox selections in PHP?

When updating multiple database records based on checkbox selections in PHP, the foreach loop can be optimized by using prepared statements to prevent SQL injection and improve performance. By binding parameters and executing the query inside the loop, you can efficiently update each selected record without the need for multiple database connections.

// Assume $checkboxes is an array containing the IDs of selected checkboxes
// Assume $conn is the database connection

$stmt = $conn->prepare("UPDATE table_name SET column_name = :value WHERE id = :id");

foreach($checkboxes as $id) {
    $stmt->bindParam(':value', $value); // Set the value to update
    $stmt->bindParam(':id', $id); // Set the ID of the record
    $stmt->execute(); // Execute the query for each selected record
}