What are the potential pitfalls of sending multiple queries within a loop in PHP?

Sending multiple queries within a loop in PHP can lead to performance issues and inefficiencies, as each query requires a connection to the database and incurs overhead. To solve this problem, you can batch multiple queries together and send them in a single request to the database, reducing the number of connections and improving performance.

// Example of batching queries in PHP
$queries = array(
    "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')",
    "INSERT INTO table_name (column1, column2) VALUES ('value3', 'value4')",
    // Add more queries as needed
);

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=my_database", "username", "password");

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

// Execute all queries in a single batch
foreach ($queries as $query) {
    $pdo->exec($query);
}

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