0

I'm trying to write a custom class for MySQLi, but I keep receiving the error "Trying to get property of non-object in" when using num_rows. Can anyone help?

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
  • mysqli::query() returns a mysql_result resource. Your query $sql fails for some reason and you perform no error check before attempting to get mysql_result::$num_rows from it. Commented Jul 8, 2012 at 20:57

1 Answer 1

1

mysqli_query() doesn't always return a mysqli_result object, it can return TRUE and FALSE as well which would result in the error you are getting.

Store the return value of query() and check to see if it is TRUE or FALSE before you try to access it as an object and fetch the num_rows property.

From the manual about mysqli::query():

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.