有几件事你的代码错误:
$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']. "'>" ....
}
你如何当你执行你的SQL查询出来的代码的结果呢? – Snoozer