1

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?

2
  • Sorry, but how could i do this var_dump($data);? Commented Mar 12, 2014 at 14:26
  • Never mind, I figured out was wrong! Check my answer :) Commented Mar 12, 2014 at 14:30

3 Answers 3

10

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.

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

2 Comments

$data is not a multidimensional array.
Thank you, I just looked more into it. I'll edit my answer @RocketHazmat
2

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'];
}

Comments

1

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>

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.