显示列的sql查询输出

时间:2019-03-02 00:44:31

标签: php sql mysqli

我有这张桌子

id | apple | banana | coconut | pear|
1     1       1       1           0
2     0       0        1          1
3     1       0        0          1

和此sql查询

select tree
from ((select id, 'apple' as tree
       from trees
       where apple = 1
      ) union all
      (select id, 'banana' as tree
       from trees
       where banana = 1
      ) union all
      (select id, 'coconut' as tree
       from trees
       where coconut = 1
      ) union all
      (select id, 'pear' as tree
       from trees
       where pear = 1
      )
     ) t
where id = 1;

输出是

apple 
banana
coconut

我该如何用php写这个,以便我可以回显结果

这是我到目前为止所拥有的

$sql = " select tree
    from ((select id, 'apple' as tree
           from trees
           where apple = 1
          ) union all
          (select id, 'banana' as tree
           from trees
           where banana = 1
          ) union all
          (select id, 'coconut' as tree
           from trees
           where coconut = 1
          ) union all
          (select id, 'pear' as tree
           from trees
           where pear = 1
          )
         ) t
    where id = '$id'";
 $result = mysqli_query($conn, $sql);

但是我不知道该怎么办之后,我无法进行while循环,或者只是回显它给出错误的结果

1 个答案:

答案 0 :(得分:0)

您可以使用mysqli_fetch_assoc()简单地遍历结果:

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['tree'] . "\n";
}

但是,执行这样的操作可能更简单/更有效,该操作使用列名来生成输出数据,并在列中的值不为0时回显该名称:

$sql = "SELECT * FROM trees WHERE id = '$id'";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    foreach ($row as $key => $value) {
        if ($key == 'id') continue;
        if ($value) echo "$key\n";
    }
}