我想根据类型列出我数据库中的注释。
我的数据库中有三种类型的注释,我用三种不同的查询来调用它们。
//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
有没有办法用单个查询而不是三个查询获得相同的输出?
答案 0 :(得分:22)
PDO比每个人都认为的要多一点。例如,它有一个很棒的功能,称为PDO::FETCH_GROUP。
更不用说可以使您的代码显着缩短的其他一些小改进。
$r = $handler->query("SELECT confirmed, c.* FROM comments c")->fetchAll(PDO::FETCH_GROUP);
是您需要的所有代码。
在这里,您首先选择confirmed
字段,然后告诉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>";
}
}
答案 1 :(得分:2)
是的,您可以使用IN
条件:
SELECT * FROM comments WHERE confirmed IN (0, 1, 2)
然后,您可以根据需要循环遍历结果以创建输出。
答案 2 :(得分:2)
您可以使用此查询语法:
SELECT * FROM comments
WHERE (confirmed >= 0 AND confirmed < 3 )
ORDER BY FIELD(confirmed,0,2,1)
通过这种方式,您可以按所需的输出排序所有行。
如果confirmed
字段仅允许0,1,2值,您可以这样方式:
SELECT * FROM comments
ORDER BY FIELD(confirmed,0,2,1)
然后:
while( $row = $query->fetch(PDO::FETCH_ASSOC) )
{
if ( $row['confirmed'] == 0 )
{
(...)
}
elseif( $row['confirmed'] == 1 )
{
(...)
}
else
{
(...)
}
}
答案 3 :(得分:0)
你可以这样做:
SELECT * FROM comments WHERE confirmed=1 OR confirmed=2 OR confirmed=0
或者使用IN