我能够从数据库中检索和显示一行数据,但是我想检索多个数据。我的代码搞砸了,但是我认为我要在正确的区域进行这项工作。
我的代码:
$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;
?>
最佳答案
您的代码有些错误:
$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']. "'>" ....
}
关于php - 在PhP中显示多行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33567896/