PDO查询致命错误:在非对象上调用成员函数setFetchMode()

时间:2012-05-02 15:02:09

标签: php database pdo fetch

我一直在尝试在我的sql数据库中提取$ user等于subscriberID的所有信息。我正在使用PDO方法插入数据并希望也使用查询功能。 我从我的尝试条件中收到以下错误消息。

致命错误:在非对象

上调用成员函数setFetchMode()

我考虑过这个问题可能是由我用来拉取数据的方法引起的,因为它对于PDO来说是相当新的。(我包括一个建立数据库链接的top.php)

感谢您的建议

 <?php
 include "top.php";

    try{
        $user = $_SESSION['login'];
        echo "Welcome <strong>$user</strong> to your saved holidays";

        //$getSavedHolidays = $db->query("SELECT * FROM saved_holidays WHERE subscriberID='$user'");
        //preparing a PDO statment for accessing saved holidays when the logged in user matchs the subscriberID
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
        //uses a bind valu as this makes the statment more secure
        $getSavedHolidays->bindValue(":user", $_SESSION['login']);
        $getsavedHolidays->setFetchMode(PDO::FETCH_ASSOC);
        $getSavedHolidays->execute();


        foreach ($Result as $row)
            {
                echo "<p><a href'".$row['link']."'>".$row['title']."</a><br \>" . 
                     $row['description'] . "<br \>" . 
                     $row['pubDate'] ."<br \></p>";
            }

        }

        catch (PDOException $e) 
            {
                 print_r($e->errorInfo);
                    die();
            }

&GT;

2 个答案:

答案 0 :(得分:4)

你应该准备你的陈述。它有一个额外的好处,即更安全,而且它将解决您的问题。

$user = $_SESSION['login'];

try {
    $db = new PDO("mysql:host=localhost;dbname=database", "user", "pass");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
    $getSavedHolidays->bindValue(":user", $_SESSION['login']);
    $getSavedHolidays->setFetchMode(PDO::FETCH_ASSOC);
    $getSavedHolidays->execute();
    $Result = $getSavedHolidays->fetchAll();

    foreach ($Result as $row) {/*...*/}

}
catch (PDOException $e) {
    print_r($e->errorInfo);
    die();
}

修改

您在上面粘贴的代码中有错误:

$$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");

应该是

$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");

答案 1 :(得分:2)

存在明确的语法错误。缺少关闭单引号:

$getSavedHolidays = $db->query("SELECT * FROM saved_holidays WHERE subscriberID='$user'");

顺便说一句,既然你正在使用PDO,那么使用bindValue函数将值传递给SQL请求会更安全。