0

I've got an stdClass coming from my database :

$query = $this->db->get('news');

if(isset($options['id']) || $options['limit'] == 1)
    return $query->row(0);

And I would like to pass it to my variable :

$data['news'] = $this->front_model->getNews($spec);

so that I can get to any property simply by doing $data['news']->id

but I get this message error:

Message: Object of class stdClass could not be converted to string

why?

ghbarratt
  • 11,496
  • 4
  • 41
  • 41
Miles M.
  • 4,089
  • 12
  • 62
  • 108
  • What is `$this->db`? Are you using a framework like CodeIgniter? – Jonathon Reinhart Aug 03 '12 at 01:33
  • 2
    What your `getNews` returns ? `var_dump($data['news'])` and check what you've got. – The Alpha Aug 03 '12 at 01:37
  • 1
    If you are using CodeIgniter then you can use `return $query->row_array(0)` but I don't really think that is what is causing the error message. – ghbarratt Aug 03 '12 at 01:48
  • Yes I'm using code Igniter, I know I cans use $query->row_array(0) but i would like to keep it as an stdclass, and put it into my $data variable that I pass to the view. – Miles M. Aug 03 '12 at 01:53
  • @ghbarratt My var_dump show me what'im lookig for, in fact, it is working, but I still have that error at the top of the page. When I mean it works, I mean I can access $data['news']->id anyway – Miles M. Aug 03 '12 at 01:55
  • Perhaps the error is actually occurring in the view? A stdClass can be fairly easily cast into an array but I thought you could use stdClass just as easily as an array in the view. Can you show us your view code? – ghbarratt Aug 03 '12 at 02:04

1 Answers1

2

Instead of

return $query->row(0);

Use this

return $query->row_array(0);

It will already fetch the result in array form

http://codeigniter.com/user_guide/database/results.html

first remove the 0 from $query->row() because it only fetches single record. then print_r($data) to see what is coming

Also do this

$news = $this->front_model->getNews($spec);

instead of

$data['news'] = $this->front_model->getNews($spec);

Now you are able to call it like this

echo $news->id;
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
  • yeah but the thing is I'm looking to use it as an stdClass so that I can access my variable this way : $news->id instead of $news['id'] – Miles M. Aug 03 '12 at 03:39
  • okay, but how do I pass it into the view then ? Because I'm passing an array : $data , and nothing else. "first remove the 0 from $query->row() because it only fetches single record" => that was intentional ;) – Miles M. Aug 03 '12 at 17:46