简体   繁体   中英

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

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 :

在此处输入图片说明

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

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

在此处输入图片说明

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

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.

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 ($cours->result() as $row) {
        $data[] = $row;
    }
    return $data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM