PDO While 循环导致无限循环

PDO While loop causing infinite loop

我有一个 PDO 对象连接到数据库以显示属性,我正在尝试使用 if 语句在没有找到任何行时显示一条消息。该消息有效,但是当找到结果时,循环返回无穷无尽的行并中断我的 css。

唯一一次它起作用的时候是我在循环括号内定义了我的循环条件,然后是我的 if 语句条件 returns a "undefined variable error"。我怎样才能让两者一起工作,我已经查看了其他问题并尝试了不同的方法但没有得到任何结果。

//代码

<?php function connectDB () {

    global $hostname, $db, $user, $pass;

    $dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    if (stripos($_SERVER['REQUEST_URI'], 'sales.php')) {
         $sql = "SELECT * FROM DATABASE.property WHERE (bit1&33=33 and sendToPortals ='0') and (addressToDisplay like ? or fullDetails like ?) ORDER BY pricePerWeek ASC";
    }
    else if (stripos($_SERVER['REQUEST_URI'], 'lettings.php')) {
         $sql = "SELECT * FROM DATABASE.property WHERE bit1&17=17 and (addressToDisplay like ? or addressToDisplay like ?) ORDER BY pricePerWeek ASC";
    }

    $query = $dbh->prepare($sql);
    $query->execute(array('%Bedford Court Mansions%','%Adeline Place%')); 
    $query->setFetchMode(PDO::FETCH_ASSOC); 
    $r = $query->fetch();

        if (!$r) {
        echo 'We have successfully Sold 
            all their current property within Bedford Court Mansions, WC1 and urgently require 
            new apartments for sale.
            Call us now on 020 72459 3345, if you are considering 
            selling your property.';
        } 
        else { 

        while ($r): 

            $address = $r['addressToDisplay']; 
            $beds = $r['bedrooms'];
            $price = $r['price_week_min'];
            $summary = $r['summary'];
            $image = $r['mainImage'];
            $area = $r['addressAlias'];
            $id = $r['id'];

            $address1 = str_replace(' ','-',$address);
            $address2 = str_replace(',','',$address1);
?>

    <li class="property">
        <div class="image-wrapper overlay-fade-in">
            <img src="http://www.hurford-salvi-carr.co.uk/pss/image-resize?height=257&width=449&black=1&reflection=0&prop=0&asset=pictures&file=<?php echo $image; ?>" />
            <div class="image-overlay-content">
                <h2>
                    <a href="http://www.hurford-salvi-carr.co.uk/property-for-sale/<?php echo strtolower(str_replace(' ','-',$area)); ?>/<?php echo strtolower(str_replace(' ','-',$address)); ?>/<?php echo $id; ?>" target="_blank">Find out More</a>
                </h2>
            </div>
        </div>

        <div class="property-content">
            <h3><?php echo $address; ?></h3>
            <p><strong>£ <?php echo number_format($price); ?> </strong></p>
            <p><strong><?php echo $beds; ?> &nbsp; Beds</strong></p>
            <p>
                <?php echo substr($summary, 0, 263); ?>...</p>
            <a href="http://www.hurford-salvi-carr.co.uk/property-for-sale/<?php echo strtolower(str_replace(' ','-',$area)); ?>/<?php echo strtolower(str_replace(' ','-',$address)); ?>/<?php echo $id; ?>" target="_blank">Click here to find out more</a>
        </div>
    </li>

<?php           
        endwhile; }}
?>

如评论中所述,问题的根源在于您始终检查 while 语句中的变量,而不是实际的 fetch() 方法。这反过来看起来像 while (true),它创建了从数据库返回的第一行的无限循环。

要检查数据库中是否有任何结果,请检查 SELECT 查询返回的行数,如果它不为 0,则可以遍历结果。如果为 0,则显示一条好消息,告诉他们没有找到任何东西。

<?php 
$query = $dbh->prepare($sql);
$query->execute(array('%Bedford Court Mansions%','%Adeline Place%')); 
$query->setFetchMode(PDO::FETCH_ASSOC);
$numRows = $query->rowCount();

if ($numRows == 0) {
    // No rows returned from database
} else { 
    // We have results!
    while ($query->fetch()): 
        // Loop through it all
?>

参考: