在php中的foreachloop中使用while循环执行mysqlquery


doing a mysql_query with while loop inside foreachloop in php

嗨,我正在尝试查看xml结果的列表,我正在从这些结果中获取id,并在数据库中执行查询以获取更多信息。我已经将其放入foreach循环中,然后让while循环获得mysql结果。在我做while循环之前,一切都正常。我的页面是空白的,没有任何错误。。任何帮助都将不胜感激!这是我的代码:

foreach($data->HotelList->HotelSummary as $info):
    $hotelId = $info->hotelId;
    $title=$info->name;
?>
<!---------------------------------------------------------------------->
<!-----------------Listed hotel results div----------------------------->
<!---------------------------------------------------------------------->
<div class="listResults">
    <div class="hotelListing">
    <div class="hotelThumb">
    <?php 
    //----------Getting thumb url from database by HotelId-------
    $getImages = mysql_query("SELECT Caption FROM HotelImages WHERE ID = '4110'") or die(mysql_error());
    while($r=$mysql_fetch_array($getImages)):
        $img = $r['Caption'];
    ?>
    <img src="" width="200" height="180" alt="test image" class="thumb" />
    <?php endwhile; ?></div>
<?php endforeach; ?>

注意,我已经尝试过获取num_rows,但我确实得到了正确的结果。所以查询正在执行,但是while循环中发生了一些事情。

while循环不好。取出函数前面的$

while($r=mysql_fetch_array($getImages)):

您的主要问题是将$放在方法调用($mysql_fetch_array())前面。它应该只是mysql_fetch_array()

不应该忽略的一个重要问题是,在循环中调用了一个静态查询。在循环的外部执行查询,因为结果永远不会改变。然后,您可以将结果存储在一个数组中,并在循环中迭代该数组。这将显著提高代码的性能。

<?php
//----------Getting thumb url from database by HotelId-------
$getImages = mysql_query("SELECT Caption FROM HotelImages WHERE ID = '4110'") or die(mysql_error());
$images = array();
while($img = mysql_fetch_array($getImages)) {
    $images[] = $img['Caption'];
}
foreach($data->HotelList->HotelSummary as $info):
    $hotelId = $info->hotelId;
    $title=$info->name;
?>
<!---------------------------------------------------------------------->
<!-----------------Listed hotel results div----------------------------->
<!---------------------------------------------------------------------->
<div class="listResults">
    <div class="hotelListing">
    <div class="hotelThumb">
    <?php 
    foreach($images as $img) :
    ?>
    <img src="" width="200" height="180" alt="test image" class="thumb" />
    <?php endforeach; ?></div>
<?php endforeach; ?>
while($r=$mysql_fetch_array($getImages)):
    $img = $r['Caption'];
?>

您在mysql_fetch_array()之前有一个$,删除它应该可以解决您的问题。