douweida2669 2016-12-15 17:04
浏览 38
已采纳

pdo选择一次特定行

I want to return Title only once and then a list of all users with correct n_id.

I have such table:

| N_ID |  USER | TITLE  |
|------|-------|--------|
| 1    | User1 | Title1 |
| 1    | User2 | Title1 |
| 1    | User3 | Title1 |
| 2    | User3 | Title5 |

My code so far:

$sql = $this->conn->prepare("SELECT * FROM n_list WHERE n_id = :id");
$sql->bindparam(":id", $id);
$sql->execute();
while($rows = $sql->fetch(PDO::FETCH_ASSOC)) 
{
echo 'Title: '.$rows["title"].' <br></br>';
echo $rows["user"];
}

Currently it gives me this:

Title: Title1
User1
Title: Title1
User2
Title: Title1
User3

I need this as a result:

Title: Title1
User1
User2
User3

How do I get the title row before while loop? Do I add another fetch there or I add another query?

I am new to pdo so sorry if the solution looks obvious to you!

  • 写回答

1条回答 默认 最新

  • dongtuota3633 2016-12-15 17:19
    关注

    Seeting a flag to know the title has printed should work.

    $sql = $this->conn->prepare("SELECT * FROM n_list WHERE n_id = :id");
    $sql->bindparam(":id", $id);
    $sql->execute();
    
    $flagtitle = 0;
    
    while($rows = $sql->fetch(PDO::FETCH_ASSOC)) 
    {
      if($flagtitle == 0){
        echo 'Title: '.$rows["title"].' <br>';
        $flagtitle = 1;
      }
      echo $rows["user"].'<br>';
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案