Search code examples
phpmysqlquery-performance

Is it possible to avoid query in loop?


I have such code:

$q = "SELECT date FROM t1 GROUP BY date";
$pdo->query($q);
$results = $pdo->results();

foreach($results as $result) {
    echo "<h1>$result['date']</h1>";
    echo "<table>";

    $q = "SELECT * FROM t1 WHERE date=:date";
    $pdo->query($q);
    $pdo->bind("date", $result['date']);
    $subresults = $pdo->resultset();

    foreach($subresults as $sub) {
        echo "<tr><td>$sub['smth']</td></tr>";
    }

    echo "</table>";
}

It reads dates from database and prints separate tables with data. It is possible to achieve this without having query in a loop?


Solution

  • You can order the results by date, instead of group by. Then, you can use some if conditions to render the h1 and table tags:

    $q = "SELECT `smth`, `date` FROM `t1` ORDER BY `date`";
    $pdo->query($q);
    $results = $pdo->results();
    
    $currentDate = '';
    foreach($results as $index => $result) {
        if ($currentDate != $result['date']) {
            if ($index != 0) {
                echo "</table>";
            }
    
            echo "<h1>{$result['date']}</h1>";
            echo "<table>";
        }
    
        echo "<tr><td>{$result['smth']}</td></tr>";
    
        $currentDate = $result['date'];
    }
    
    echo "</table>";
    

    NB: Not tested