查询结果不循环

时间:2014-08-13 12:29:58

标签: php mysqli

我在我的数据库上设置了一个mysqli查询。我一直在尝试循环结果以显示多行行,并且已经遵循了许多有关如何执行此操作的教程。但是,我仍然只在页面上出现一行。任何帮助解决这个问题都将受到赞赏。

$query2 = $con->query("SELECT * FROM journeys WHERE id = $id");
$count = mysqli_num_rows($query2);

if($count == 0) {
    $journeys = 'You have no future journeys.';
}
else{
    $result = $con->query($query2);
    while ( $row = $query2->fetch_assoc() ) {

    $journeys = "{$row['origin']}-{$row['destination']}<br />{$row['date']}<br />{$row['hour']}:{$row['minute']}";
}

    }

3 个答案:

答案 0 :(得分:2)

你的问题在这里:

$journeys = "{$row['origin']}-{$row['destination']}<br />{$row['date']}<br />{$row['hour']}:{$row['minute']}";

您在每次循环迭代时分配$journeys,这将替换旧内容,因此$journeys将仅包含查询中最后一行的数据。您需要将这些添加到数组中,例如

while(...)
    $journeys[] = "{$row['origin']}-{$row['destination']}<br />{$row['date']}<br />{$row['hour']}:{$row['minute']}";

请注意,赋值中的空数组下标只是分配给下一个可用索引。

然后迭代数组以打印它,例如

foreach($journeys as $journey)
    echo $journey;

答案 1 :(得分:1)

无需再次运行$result = $con->query($query2);,因为$ query2已经有结果。

答案 2 :(得分:1)

$query2 = $con->query("SELECT * FROM journeys WHERE id = $id");

//chck the query execution status
if ($query2) 
{
    //print error message
    printf("Connect failed: %s\n", $mysqli->error);
    exit();
}
else
{
    //get the count of the result
    $count = $query2->num_rows;

    if($count == 0) 
    {
        $journeys = 'You have no future journeys.';
    }
    else
    {
        $data = array();

        //process each row
        while ( $row = $query2->fetch_assoc() )
        {
            //display the result
            echo "{$row['origin']}-{$row['destination']}<br />{$row['date']}<br />{$row['hour']}:{$row['minute']}";

           // dumb into array
           // $data[] = "{$row['origin']}-{$row['destination']}<br />{$row['date']}<br />{$row['hour']}:{$row['minute']}";
        }

                //print the result
        //print_r($data);

    }
}