What are the potential pitfalls of using database queries within loops in PHP?

Using database queries within loops in PHP can lead to performance issues and inefficient use of database resources. Each query executed within a loop incurs overhead for establishing a connection, sending the query, and fetching results. To solve this problem, it is recommended to fetch all necessary data with a single query before entering the loop, and then iterate over the fetched data within the loop.

// Fetch data before entering the loop
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        // Process data within the loop
    }
}