我有这张桌子
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_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";
}
}