有幾件事你的代碼錯誤:
$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