在PhP中显示多行

时间:2015-11-06 13:26:39

标签: php mysql

我能够从数据库中检索并显示一行数据,但我想检索多个数据。我的代码搞砸了,但我认为我要进入正确的领域只需要做这项工作。

我的代码:

    $query = "SELECT * FROM hotel";
$results = $conn->query($query);
    while($hotel = $results->fetch()) { echo "<br> id: ". $hotel['hotel_id']. " - Name: ". $hotel['name']. " - Address: " . $hotel['address'] . " - Postcode: " .
$hotel['postcode']. " - Town: " . $hotel['town']. " - Description: ". $hotel['description']. " - rating: ". $hotel['rating']. " - image: " . <img src='". $hotel['image']. "'>"";
    }
$conn=NULL;
?>

3 个答案:

答案 0 :(得分:1)

您的代码存在一些问题:

$query = "SELECT * FROM hotel";
$results = $conn->query($query);
$hotel = $results->fetch();

此时,您已将第一条记录加载到$hotel。如果您想要遍历记录集,则无需执行此操作。

$hotel[$id] = $hotel['hotel_id'];
$hotel[$name] = $hotel['name'];
$hotel[$address] = $hotel['address'];
$hotel[$postcode] = $hotel['postcode'];
$hotel[$town] = $hotel['town'];
$hotel[$description] = $hotel['description'];
$hotel[$rating] = $hotel['rating'];
$hotel[$image] = $hotel['image'];

这些行有些多余。您已经在$hotel中获得了行的详细信息,并且您正在使用尚未定义的数组键添加额外的条目。

/*
$id = $hotel['hotel_id'];
$name = $hotel['name'];
$address = $hotel['address'];
$postcode = $hotel['postcode'];
$town = $hotel['town'];
$description = $hotel['description'];
$rating = $hotel['rating'];
$image = $hotel['image'];
*/
while($hotel = $results->fetch()) {
    echo "<br> id: ". $hotel[$id] = $hotel[id]. " - Name: ". $hotel[$name]. " - Address: "     . $hotel[$address] . " - Postcode: " . $hotel[$postcode].
    " - Town: " . $hotel[$town]. " - Description: ". $hotel[$description]. " - rating: ". $hotel[$rating]. " - image: " . $hotel[$image];
}

在你的循环中,你正试图错误地访问数组键。 $hotel[$id]使用$id作为密钥,该变量不存在。 $hotel[id]使用的是一个不带引号的密钥,PHP会猜测它是$hotel['id'],但会抱怨。所以你可以直接引用它来避免警告。

因此,您可以将代码简化为:

$query = "SELECT * FROM hotel";
$results = $conn->query($query);

while($hotel = $results->fetch()) {
    echo "<br> id: ". $hotel['id'] . " - Image: <img src='". $hotel['image']. "'>"  ....
}

答案 1 :(得分:0)

我看到你正在使用PDO。你可以简单地遍历这样的结果。

while($results_disp = $results->fetch(PDO::FETCH_OBJ))
{
//access rows here in this manner
echo "Hotel Id :- " . $results_disp->id;
}

答案 2 :(得分:0)

1
10
2
3
4
5
6
7
8
9

用此替换你的while循环。