php – 如何多个查询结果以减少查询数量?

前端之家收集整理的这篇文章主要介绍了php – 如何多个查询结果以减少查询数量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想根据类型列出我数据库中的注释.

我的数据库中有三种类型的注释,我用三种不同的查询调用它们.

//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>";
    }
}

猜你在找的PHP相关文章