简体   繁体   中英

UNION query works in mysql but doesn't work the same in php

When I run this query in mysql it returns all the requested results correctly:

SELECT row_id FROM table1 WHERE status = n 
UNION ALL 
SELECT row_id FROM table2 WHERE status = n 
UNION ALL 
SELECT row_id FROM table3 WHERE status = n

However when I run it from PHP it returns only one record, the first row that meets the requested condition.

$query = mysqli_query($link, "SELECT row_id FROM table1 WHERE status = n 
UNION ALL 
SELECT row_id FROM table2 WHERE status = n 
UNION ALL 
SELECT row_id FROM table3 WHERE status = n");

print_r(mysqli_fetch_array($query));

So print_r shows the following: Array ( [0] => 1 [row_id] => 2580 ) , where 2580 is a id of the row from table1 that meets the requested condition.

How to make it return the full array of results?

You can try to print data in loop like:

$query = mysqli_query($link, "SELECT row_id FROM table1 WHERE status = n 
UNION ALL 
SELECT row_id FROM table2 WHERE status = n 
UNION ALL 
SELECT row_id FROM table3 WHERE status = n");

while($row = mysqli_fetch_array($query)){
    print_r($row);
}

Simply mysqli_fetch_array only return current row in the loop. You need to loop through it to get all the results.

  1. I never knew that WHERE status = n is valid SQL. Shouldn't it be WHERE status = 'n'
  2. Try looping your mysqli_fetch_array() like this:

while($row = mysqli_fetch_array($query)){ print_r($row); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM