PDO is a little more than everyone thinks. For example, it has a great function for you called PDO :: FETCH_GROUP .
Not to mention other small improvements that can make your code much shorter.
$r = $handler->query("SELECT confirmed, c.* FROM comments c")->fetchAll(PDO::FETCH_GROUP);
Anything you need.
here you first select the confirmed field, and then indicate the PDO to group (or "multiply") the results based on its value.
And now you can print your comments wherever you want
// Awaiting Comments foreach($r[0] as $r_) { echo "<li>$r_[title]</li>"; } // Confirmed comments foreach($r[2] as $r_) { echo "<li>$r_[title]</li>"; }
Or to do it in one loop
$titles = [ 0 => 'Awaiting Comments', 2 => 'Comments waiting confirmation', 1 => 'Confirmed Comments', ]; foreach ($titles as $code => $title) { echo "<h3>$title</h3>"; foreach($r[$code] as $r_) { echo "<li>$r_[title]</li>"; } }
source share