如何分别循环多个SELECT

时间:2013-01-26 08:33:09

标签: php

我有两个查询,我希望在单独的while循环中得到结果,查询工作正常,但我无法弄清楚如何在while循环中分离结果。

PHP

$query = "
SELECT 1 as query, title FROM $tablename WHERE category='category1' LIMIT 10
UNION
SELECT 2 as query, title FROM $tablename WHERE category='category2' LIMIT 10
";

$result = mysqli_query($connection, $query) or trigger_error(mysqli_error($connection), E_USER_ERROR);

while($row = mysqli_fetch_assoc($result[1])){
    echo $row['title'].'<br />';
}
while($row = mysqli_fetch_assoc($result[2])){
    echo $row['title'].'<br />';
}

请参阅并建议任何可行的方法。

3 个答案:

答案 0 :(得分:1)

$query = "
  SELECT 1 as query, title FROM $tablename WHERE category='category1' LIMIT 10
  UNION
  SELECT 2 as query, title FROM $tablename WHERE category='category2' LIMIT 10
";

$result = mysqli_query($connection, $query) or trigger_error(mysqli_error($connection), E_USER_ERROR);

while($row = mysqli_fetch_assoc($result)){
    echo $row['title'].'<br />';
}

就是这样。 while循环的每次迭代都会检索下一个结果。

答案 1 :(得分:1)

$query = "
SELECT 1 as query, title FROM $tablename WHERE category='category1 LIMIT 10'
UNION
SELECT 2 as query, title FROM $tablename WHERE category='category2 LIMIT 10'
";

$result = mysqli_query($connection, $query) or trigger_error(mysqli_error($connection), E_USER_ERROR);

$qResult1 = array();
$qResult2 = array();

while($row = $result->fetch_assoc()){
    if($row['query'] == 1) $qResult1[] = $row;
    else $qResult2[] = $row;
}

答案 2 :(得分:1)

为什么不分开两个查询?

$query1 = "SELECT title FROM $tablename WHERE category='category1' LIMIT 10";

$result = mysqli_query($connection, $query1) or trigger_error(mysqli_error($connection), E_USER_ERROR);

while($row = mysqli_fetch_assoc($result1)){
    echo $row['title'].'<br />';
}

$query2 = "SELECT title FROM $tablename WHERE category='category2' LIMIT 10";
$result = mysqli_query($connection, $query2) or trigger_error(mysqli_error($connection), E_USER_ERROR);

while($row = mysqli_fetch_assoc($result2)){
    echo $row['title'].'<br />';
}

或者您可以循环播放类别。

$catgories = array('category1', 'category2');

foreach($categories as $cat){
    $query = "SELECT title FROM $tablename WHERE category = {$cat} LIMIT 10";
    $result = mysqli_query($connection, $query) or trigger_error(mysqli_error($connection), E_USER_ERROR);
    echo $cat.'<br />'
    while($row = mysqli_fetch_assoc($result)){
        echo $row['title'].'<br />';
    }