0

I'm using the codeigniter framework, I'm retrieving data from the database in the form of an array but when i try to use the foreach function to display the data i get an error

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

this is the array

Array  
(
[0] => stdClass Object
    (
        [id] => 1
        [title] => title
        [data] => data
    )


)

*The foreach is

foreach($data as $r) echo $r  
1
  • 1
    Where's the code (the foreach)? Commented Sep 15, 2010 at 14:30

3 Answers 3

2

If you try it like this it should work:

<?php foreach($data as $r): ?>
    <?php echo $r->id; ?><br>
    <?php echo $r->title; ?><br>
    <?php echo $r->data; ?><br>
<?php endforeach; ?>
Sign up to request clarification or add additional context in comments.

10 Comments

Oh my gosh! What purpose does this code have? I guess most of the users prefer not to put every single command inside <?php ?>. It's considered as bad coding style.
This assumes you are in the view where you usually do most of your iterating over database records.
IMHO this assumes way too much: Not every piece of code is meant to be outputted in HTML. And even if so, then why would you seperate the first line from the first echo? IT's more work for the interpreter and it's not easy readable for humans. Just my 2cents
thats perfect ! except you should use the shorthand <?php foreach() : ?> i think it makes it look nicer . but thanks
@Jan using PHP code in HTML like this is totally acceptable IMO and I can't see how this is less future-oriented than using a full-blown templating system (that replicates what PHP does anyway) - as long as you stick to variables and simple control structures. PHP operations and calculations inside HTML is what's evil. (I am a happy user of template engines in many projects by the way, but they're not always needed.)
|
2

Look close! You are putting the outter Array into the foreach loop. Every "$r" is then one Object with the properties id, title, data.

Try

foreach ($data as $k => $r) {
    echo $r->id;
}

Comments

0

The problem is in echo $r. $r is of type stdClass, which can not be printed like that. Try print_r($r).

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.