在非对象上调用成员函数fetchAll()

时间:2015-10-09 02:11:36

标签: php pdo

我正在尝试PDO,我遇到了这个错误:

  

在非对象

上调用成员函数fetchAll()

我无法弄清楚它为什么会抛出错误?函数$con->query()完美地工作,但无法弄清楚为什么预处理语句失败!任何帮助将不胜感激。

<?php 
function connect_to_db($host, $db, $user, $pass)
    {
        try{
            $con = new PDO("mysql:host={$host};dbname={$db}", $user, $pass);
            $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $con;
        }catch(PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }

function prepare_query($con, $query="", $bindings=array())
    {
        try{
            $stmt = $con->prepare($query);
            return $stmt->execute($bindings);
            //return $con->query('SELECT * FROM user_details');

        }catch(PDOException $e){
            throw new Exception($e->getMessage());
        }
    }

function close_connection($con)
    {
        try{
            return $con = NULL;
        }catch(PDOException $e){
            throw new Exception($e->getMessage());
        }   
    }

try {
        $con = connect_to_db('localhost', 'crazybrains', 'root', 'toor');
        $query = 'SELECT * FROM user_details WHERE id = :id';
        $bindings = array('id' => 8);
        $stmt = prepare_query($con, $query, $bindings);

        while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)){
            echo "<pre/>";
            print_r($row);
        }

        close_connection($con);

        //echo 'connection established';
    } catch(Exception $e) {
        echo $e;
}
?>

0 个答案:

没有答案