Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...