What are the potential pitfalls of querying data within loops in PHP, and how can this be avoided to improve performance?

Querying data within loops in PHP can lead to performance issues due to the overhead of making multiple database connections. To improve performance, it is recommended to query the data outside of the loop and store it in an array or object before iterating over it.

// Example of querying data outside of the loop for improved performance

// Query data from the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Store the data in an array
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

// Iterate over the data
foreach ($data as $row) {
    // Process each row
}