UNION查询在mysql中工作,但在php中不起作用

时间:2014-03-05 13:44:00

标签: php mysql sql

当我在mysql中运行此查询时,它会正确返回所有请求的结果:

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

然而,当我从PHP运行它时,它只返回一条记录,第一行符合请求的条件。

$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));

因此print_r显示以下内容:Array ( [0] => 1 [row_id] => 2580 ),其中2580是 table1 中符合请求条件的行的 id 。< / p>

如何让它返回完整的结果数组?

2 个答案:

答案 0 :(得分:0)

您可以尝试循环打印数据,如:

$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);
}

简单地说mysqli_fetch_array只返回循环中的当前行。你需要遍历它以获得所有结果。

答案 1 :(得分:0)

  1. 我从来不知道WHERE status = n是有效的SQL。不应该是WHERE status = 'n'
  2. 尝试循环使用此mysqli_fetch_array()
  3. while($row = mysqli_fetch_array($query)){ print_r($row); }