Call to a member function num_rows() on a non-obje

2019-02-19 17:00发布

I'm using CodeIgniter, and I want to get some data from a table in a database.

in my Model, I have this function :

public function fetch_cours($limit, $start, $element) {

        $id_element = $this->db->from('element')
                               ->where('name',$element)
                               ->limit(1)
                               ->get()
                               ->result();

        $query = $this->db->from('cour')
                           ->where('id_element',(int) $id_element[0]->id)
                           ->limit($limit, $start)
                           ->get()
                           ->result();
        var_dump($query);

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }

I want this function to return some records in the cour table.

In my controller I have this line :

$cours = $this->cours_m->fetch_cours(10,0,'Programmation Orientée Objet (Java)');

When I call my controller I get this message :

enter image description here

The line 38 is : if ($query->num_rows() > 0) {

So I did a var_dump($query) and this is the output :

enter image description here

What's the problem ? and how can I solve it ?

2条回答
闹够了就滚
2楼-- · 2019-02-19 17:10

Calling ->result(), you have the result of the query execution in an array. You might call your variable like this, for example :

$cours = $this->db->from('cour')
    ->where('id_element',(int) $id_element[0]->id)
    ->limit($limit, $start)
    ->get()
    ->result();

Then change your test as :

if (count($cours) > 0) {
    foreach ($query->result() as $row) {
        $data[] = $row;
    }
    return $data;
}
查看更多
女痞
3楼-- · 2019-02-19 17:15

When you create the $query variable you already added a ->result().

So $query is an array of row objects.

You should change the if to this:

if (count($query) > 0) {

And probably rename the variable to $results for example.

查看更多
登录 后发表回答