“试图获取非对象的属性” - 自定义mysqli类

时间:2012-07-08 20:48:57

标签: php

我正在尝试为MySQLi编写自定义类,但在使用num_rows时,我一直收到错误“试图获取非对象的属性”。有人可以帮忙吗?

class db { 
    private $host = "***";
    private $user = "***";
    private $pass = "***";
    private $database;

    private $connection;
    private $result;
    public $sql;

    function __construct($database) {
        if (!empty($database)) $this->database = $database;
        $this->connection = new mysqli($this->host,$this->user,$this->pass,$this->database);
        return $this->connection;
    }

    public function fetchRowNum($sql) {
        if (!empty($sql)) {
            $this->sql = $sql;
            return $this->connection->query($sql)->num_rows;
        } else {
            throw new Exception("Error fetching row");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

mysqli_query()并不总是返回mysqli_result个对象,它也会返回TRUEFALSE,这会导致您收到错误。< / p>

存储query()的返回值,并在尝试将其作为对象访问并检索TRUE属性之前检查它是FALSE还是num_rows

关于mysqli::query()

的手册
  

失败时返回 FALSE 。成功 SELECT SHOW DESCRIBE 或    EXPLAIN 查询mysqli_query()将返回mysqli_result个对象。对于   其他成功的查询mysqli_query()将返回 TRUE