使用mysqli返回多行

时间:2014-08-12 11:23:31

标签: php mysqli

我正在学习mysqli,我正在尝试查询数据库并返回多行。我知道循环必须用于返回多行,但我不知道如何将其实现到我的代码中。一些帮助这样做将非常感激。

$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$count = mysqli_num_rows($query2);

if ($count == 0) {
    $journeys = 'You have no future journeys.';
} else {
    while ( $row = mysqli_fetch_assoc($query2) ) {      
        $from = $row ['origin'];
        $to = $row ['destination'];
        $date = $row ['date'];
        $hour = $row ['hour'];
        $minute = $row ['minute'];
        $journeyid = $row ['journeyid'];

2 个答案:

答案 0 :(得分:1)

试试这段代码

    <?php

$con=  mysqli_connect('localhost', 'root', '', 'your data base name');
$query2 = mysqli_query($con,"SELECT * FROM journeys where id=$id");
$count = mysqli_num_rows($query2);

if ($count == 0) {
    $journeys = 'You have no future journeys.';
    echo $journeys;
} else {
    while ( $row = mysqli_fetch_assoc($query2) ) {      
        $from = $row ['origin'];
        $to = $row ['destination'];
        $date = $row ['date'];
        $hour = $row ['our'];
        $minute = $row ['minute'];
        $journeyid =$row ['journeyid'];

        echo $from.'<br>';

    }
}

看看这行echo $ from;这将显示数据库中origin列中的所有内容,如果要显示目标,请使用此以及echo $ to; 表示你想要显示的内容就像echo $ variableName;它会显示结果;

在显示结果之前,它只会存储它,但不会显示它,

看看我改变你的这行代码

它的代码

if ($count == 0) {
    $journeys = 'You have no future journeys.';
    echo $journeys;// i added this line

我添加了一行,因为你在这里说的是,如果$ count等于零,那么$ journeys =&#39;你没有未来的旅程&#39 ;;但你没有使用echo你必须使用echo来显示结果。

如果你仍然有一些困惑,请再次询问,并尝试谷歌

答案 1 :(得分:-1)

$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$row = mysql_fetch_array($query2);
$count = count($row);

if(intval($count)>0)
  {

    for($i = 0; $i<$count; $i++)
        {
           $from[$i] = $row[$i]['origin'];
                 -------------------------------
                 ----------------------
        }
  }