查询和while循环出错


Error with query and while loop

这几天我一直在想这个问题。没有任何解决方案,我已经搜索并询问了朋友。但是没有好的结果。

当我使用$db->query();它给了我这个错误:致命错误:在非对象

上调用成员函数fetch()

当我使用prepare时,我根本得不到任何结果,只是一个空白页。

<?php
$query = $dbh->query("SELECT name, ad_offer, content, expiration_date FROM biz_ads ORDER BY id DESC LIMIT 0,5");
while($row = $query->fetch(PDO::FETCH_NUM)) {
        $name = $row[0];
        $ad_offer = $row[1];
        $content = $row[2];
        $expiration_date = $row[3];
        ?>
        <div class="name"> 
        <?php 
        echo $name;
        ?>
        <div class="ad_offer">
        <?php
        echo $ad_offer;
        ?>
        </div>
        <div class="content">
        <?php
        echo $content;
        ?>
        </div>
        <div class="expiration_date">
        <?php
        echo $expiration_date;
        ?>
        </div>
    <?php
        }
?>

任何帮助都是感激的。奇怪的是,不久前我得到了一个类似的旧查询。还是不行

<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbh = new PDO("mysql:host=$hostname;dbname=broet;", $username, $password);
?>
$query = "SELECT name, ad_offer, content, expiration_date 
         FROM biz_ads 
         ORDER BY id DESC 
         LIMIT 0,5";
$stmt = $dbh->prepare($query);
$stmt->execute()or die("error");