Kino
Kino

Reputation: 217

Message: Trying to get property of non-object in Codeigniter

I have this code in my Model page:

 public function getAll($researcherpk){
 $this->db->select('*');
 $this->db->from('research');
 $this->db->join('researcher', 'researcher = lastname');
 $this->db->where('researcherpk', $researcherpk); 
 return $this->db->get()->row_array();

But when I use it on my View Page

Age: <?php echo $data['age'];?>        // this work

<?php   foreach ($data as $v){ ?>          //this has an error

  <tr>
      <td><?php echo $v->title?></td>
      <td><?php echo $v->track_records?></td>
  </tr>
<?php } ?>

I get the error:

Message: Trying to get property of non-object

In my Controller page:

 public function researcher($researcherpk){

 $this->load->model('ResearchModel');

 $result['data'] = $this->ResearchModel->getAll($researcherpk);
 $this->load->view('researcher',$result);

 }

What do you think is the problem here? What is my alternative solution for it or changes?

Upvotes: 1

Views: 49198

Answers (3)

Albzi
Albzi

Reputation: 15609

Change your return to:

return $this->db->get()->result_array();

Then try using $v['title'] and $v['track_records']

<?php foreach ($data as $v): ?>
  <tr>
    <td><?php echo $v['title']?></td>
    <td><?php echo $v['track_records']?></td>
  </tr>
<?php endforeach; ?>

Look at the codeigniter docs to learn more.

result_array():

This function returns the query result as a pure array

That is what you want.

You are mixing it with:

row_array():

This function returns a single result row. If your query has more than one row, it returns only the first row.

This is not what you want.

Upvotes: 10

gen_Eric
gen_Eric

Reputation: 227190

You're calling row_array this means $data is an array of a single row. $data['age'] works, because age is a field in the row.

You can foreach($data as $v), but this will only loop over the fields in that particular row.

You can just do echo $data['title']. $data is not a multidimensional array.

If you want multiple rows, then use return $this->db->get()->result_array();. Then you can loop over the rows:

foreach ($data as $v){
    echo $v['age'];
    echo $v['title'];
}

Upvotes: 2

Daan
Daan

Reputation: 12236

It is an array not an object so:

Change this:

  <td><?php echo $v->title?></td>
  <td><?php echo $v->track_records?></td>

To this:

  <td><?php echo $v['title']; ?></td>
  <td><?php echo $v['track_records']; ?></td>

Upvotes: 1

Related Questions