How can you properly escape variables in a SQL query within a foreach loop in PHP to avoid errors?

When using a foreach loop in PHP to iterate over an array of variables and build a SQL query, it is important to properly escape the variables to avoid SQL injection vulnerabilities and errors. You can achieve this by using prepared statements with placeholders and binding the variables to the placeholders. This ensures that the variables are sanitized before being used in the query.

// Assuming $array is the array of variables
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");

foreach ($array as $key => $value) {
    $stmt->bindValue(':value1', $value['column1']);
    $stmt->bindValue(':value2', $value['column2']);
    $stmt->execute();
}