What is the best practice for structuring PHP code to access database results in a loop?

When accessing database results in a loop in PHP, it is best practice to fetch all the results from the database at once and then iterate over them in the loop. This minimizes the number of database queries and improves performance. Additionally, it is important to properly sanitize and validate the data retrieved from the database to prevent SQL injection attacks.

// Assume $conn is the database connection and $query is the SQL query to fetch data
$result = $conn->query($query);

if ($result->num_rows > 0) {
    // Fetch all results at once
    $rows = $result->fetch_all(MYSQLI_ASSOC);

    // Iterate over the results in a loop
    foreach ($rows as $row) {
        // Access and use data from $row
    }
} else {
    echo "No results found.";
}