How can arrays and foreach loops be utilized to streamline SQL query execution in PHP?

When executing multiple SQL queries with varying parameters, arrays and foreach loops can be utilized to streamline the process. By storing the query parameters in an array and iterating over them with a foreach loop, you can dynamically execute the queries without repeating code. This approach helps in maintaining a clean and concise code structure.

<?php

// Array of SQL queries with parameters
$queries = [
    ['SELECT * FROM table WHERE id = ?', [1]],
    ['SELECT * FROM table WHERE name = ?', ['John']],
    ['SELECT * FROM table WHERE age = ? AND gender = ?', [25, 'Male']]
];

// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Execute each query with parameters
foreach ($queries as $query) {
    $stmt = $pdo->prepare($query[0]);
    $stmt->execute($query[1]);
    
    // Process the results here
    while ($row = $stmt->fetch()) {
        // Do something with the data
    }
}

?>