在PHP函数中的foreach循环

时间:2014-04-15 13:16:40

标签: php function for-loop foreach

我试图制作一个foreach循环,它在Db表中运行,并在函数中回显它,但当我尝试这样做时,它会占用我在对象中的行,并回声对象输出的次数与行数一样多,并且不会进入表格中的下一个对象。帮助表示赞赏。这是我的代码:

function hotels_from_db() {
include 'DbConnection.php';
$sql = "select * from hotels";

$result = $mysqli->query($sql);

$row = $result->fetch_object();

    foreach ($row as $value) {   
    $foundhotel = "<h1>" . $row->hotel_name . "</h1></br>";
    $foundhotel.= $row->hotel_adress . "</br>";
    $foundhotel.= $row->hotel_postal_code . "</br>";
    $foundhotel.= $row->description;
    echo "$foundhotel";
    }  
  }

尝试这样做,但这只显示表中的最后一家酒店。

function hotels_from_db() {
include 'DbConnection.php';
$sql = "select * from hotels";

$result = $mysqli->query($sql);

$row = $result->fetch_object();
while($row = $result->fetch_object()){           
    $foundhotel = "<h1>" . $row->hotel_name . "</h1></br>";
    $foundhotel.= $row->hotel_adress . "</br>";
    $foundhotel.= $row->hotel_postal_code . "</br>";
    $foundhotel.= $row->description;
    echo "$foundhotel";
    }  

}

4 个答案:

答案 0 :(得分:2)

->fetch_object只检索一行

试试这个:

function hotels_from_db() {
include 'DbConnection.php';
$sql = "select * from hotels";
$result = $mysqli->query($sql);

while($row = $result->fetch_object()) {   
    $foundhotel = "<h1>" . $row->hotel_name . "</h1></br>";
    $foundhotel.= $row->hotel_adress . "</br>";
    $foundhotel.= $row->hotel_postal_code . "</br>";
    $foundhotel.= $row->description;
    echo "$foundhotel";
}  

}

答案 1 :(得分:0)

应该是:

function hotels_from_db() {
    include 'DbConnection.php';
    $sql = "select * from hotels";

    $result = $mysqli->query($sql);

    $row = $result->fetch_all();

    foreach ($row as $value) {   
        $foundhotel = "<h1>" . $value->hotel_name . "</h1></br>";
        $foundhotel.= $value->hotel_adress . "</br>";
        $foundhotel.= $value->hotel_postal_code . "</br>";
        $foundhotel.= $value->description;
        echo "$foundhotel";
    }  
}

答案 2 :(得分:0)

$row = $result->fetch_all(MYSQLI_ASSOC); // MAKE ARRAY ASSOCIATIVE ARRAY

foreach ($row as $value) {   
    $foundhotel = "<h1>" . $value->hotel_name . "</h1></br>";
    $foundhotel.= $value->hotel_adress . "</br>";
    $foundhotel.= $value->hotel_postal_code . "</br>";
    $foundhotel.= $value->description;
    echo "$foundhotel";
}  

}

答案 3 :(得分:0)

每次获取行都需要调用

fetch_object。 请尝试以下方法:

function hotels_from_db() {
    include 'DbConnection.php';
    $sql = "select * from hotels";

    if ($result = $mysqli->query($sql)) {

        /* fetch object array */
        while ($obj = $result->fetch_object()) {
            $foundhotel = "<h1>" . $obj->hotel_name . "</h1></br>";
            $foundhotel.= $obj->hotel_adress . "</br>";
            $foundhotel.= $obj->hotel_postal_code . "</br>";
            $foundhotel.= $obj->description;
            echo "$foundhotel";        
        }

        /* free result set */
        $result->close();
    }
}