Php 显示列的sql查询输出
我有这张桌子Php 显示列的sql查询输出,php,sql,mysqli,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
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循环或只是回显结果它给出了一个错误您可以简单地使用mysqli\u fetch\u assoc()循环您的结果: 但是,这样做可能更简单/更有效,它使用列名生成输出数据,在列中的值不是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";
}
}
$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";
}
}