对象错误:对非对象的函数查询

时间:2012-06-03 13:01:58

标签: php mysql pdo

我的代码中有错误: 致命错误:在第23行的/var/www/crud_php/core/class_ManageDatabase.php中调用非对象的成员函数query()

错误行:$query = $this->link->query("SELECT * FROM $table_name ORDER BY id ASC");

<?php

class ManageDb{
    public $link;

    function __construct() {
        include_once 'class_database.php';
        $conn = new database;
        $this->link = $conn->connect();

        return $this->link;
    }

    function getData($table_name, $id=null){
        if(isset($id)){
            $query = $this->link->query("SELECT * FROM $table_name WHERE id = '$id' ORDER BY id ASC");
        }else{
         **$query = $this->link->query("SELECT * FROM $table_name ORDER BY id ASC");**   
        }

        $rowCount = $query->rowCount();
        if ($rowCount >=1){
            $result = $query->fetchAll();
        }else{
            $result = 0;
        }

        return $result;
    }


}



?>

db connect:

<?php
include_once '../config.php';

class database {

    protected $db_conn;
    public $db_name = DB_NAME;
    public $db_host = DB_HOST;
    public $db_pass = DB_PASS;
    public $db_user = DB_USER;

    function connect() {
        try {
            $this->db_conn = new PDO("mysql:host = $this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
        } catch (PDOException $e) {
            return $e->getMessage();
        }
    }

}

?>

1 个答案:

答案 0 :(得分:1)

这意味着$this->link不是对象。您忘记在connect()方法中返回连接。在该方法中添加return $this->db_conn;

另一方面,如果出现错误则返回一个字符串非常糟糕的主意。让异常传播或终止脚本 - 但不会返回其他会在代码中导致奇怪错误的东西。 您也无法从构造函数返回任何内容。