What are the potential pitfalls of using nested SQL queries in PHP to group data from a database?

Potential pitfalls of using nested SQL queries in PHP to group data from a database include decreased performance due to multiple queries being executed, increased complexity of the code leading to harder maintenance, and potential SQL injection vulnerabilities if inputs are not properly sanitized. To solve this issue, one approach is to use a single SQL query with JOINs and GROUP BY clauses to retrieve the grouped data in a more efficient and secure manner.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to group data
$sql = "SELECT category, COUNT(*) as count FROM products GROUP BY category";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Category: " . $row["category"]. " - Count: " . $row["count"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>