i have this table
id | apple | banana | coconut | pear|
1 1 1 1 0
2 0 0 1 1
3 1 0 0 1
and this sql query
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;
the out put is
apple
banana
coconut
how would i write this in php so i can echo out the result
this is what i have so far
$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);
but i dont know what to do after this i cant put a while loop or just echo out the result it gives an error
You can simply loop over your results using mysqli_fetch_assoc()
:
while ($row = mysqli_fetch_assoc($result)) {
echo $row['tree'] . "
";
}
However, it is probably simpler/more efficient to do something like this, which uses the column names to generate the output data, echoing the name when the value in the column is not 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
";
}
}