我想根据类型列出我数据库中的注释.
我的数据库中有三种类型的注释,我用三种不同的查询来调用它们.
//01 - Awaiting Comments $query = $handler->prepare("SELECT * FROM comments WHERE confirmed = 0"); $query->execute(); $r = $query->fetchAll(PDO::FETCH_ASSOC); echo "<h1>Awaiting Comments</h1>"; foreach($r as $r_) { echo "<li>r_[title]</li>"; } //02 - Comments waiting for confirmation $query = $handler->prepare("SELECT * FROM comments WHERE confirmed = 2"); $query->execute(); $r = $query->fetchAll(PDO::FETCH_ASSOC); echo "<h1>Comments waiting for confirmation</h1>"; foreach($r as $r_) { echo "<li>r_[title]</li>"; } //03 - Confirmed comments $query = $handler->prepare("SELECT * FROM comments WHERE confirmed = 1"); $query->execute(); $r = $query->fetchAll(PDO::FETCH_ASSOC); echo "<h1>Confirmed Comments</h1>"; foreach($r as $r_) { echo "<li>r_[title]</li>"; }
Awaiting Comments -comment 1 -comment 8 -comment 5 Comments waiting confirmation -comment 9 -comment 4 -comment 2 Confirmed Comments -comment 3 -comment 6 -comment 7
PDO比每个人都认为的要多一点.例如,它有一个很棒的功能,称为
PDO::FETCH_GROUP.
更不用说可以使您的代码显着缩短的其他一些小改进.
$r = $handler->query("SELECT confirmed,c.* FROM comments c")->fetchAll(PDO::FETCH_GROUP);
是您需要的所有代码.
在这里,您首先选择已确认的字段,然后告诉PDO根据其值对结果进行分组(或“乘以”).
现在,您可以随时随地打印您的评论
// Awaiting Comments foreach($r[0] as $r_) { echo "<li>$r_[title]</li>"; } // Confirmed comments foreach($r[2] as $r_) { echo "<li>$r_[title]</li>"; }
或者,使它在一个循环中
$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>"; } }