1

CodeIgniter question: So I select data from db and I am printing the results like this:

foreach ($query->result() as $row)
{       
   echo $row->db_item;
}

Foreach returns 3 rows and the result look like this: 010203.

How do I make it so the result should be echoed like this (each row of the result to be sliced somehow, e.g. each row of the result to be retrieved separately):

01
02
03

One last thing, if I add another line after the foreach I only retrieve the last row of the result 03 and not the same 010203. Why is that, theoretically?

foreach ($query->result() as $row)
    {       
       echo $row->db_item;
    }
    echo $row->db_item; //this returns 01020303
1
  • 1
    you're dumping to a web browser context, which means you have to use html means of providing line breaks, e.g. <br> Commented Feb 19, 2015 at 18:03

1 Answer 1

5

Use an html line break

echo $row->db_item ."<br>";

or a newline character.

echo $row->db_item ."\n";

or both "<br>\n"


about the foreach loop:

echo $row->db_item; //this returns 01020303

that line actually prints out 03 but since you're not using line breaks, it just tacks 03 onto the end of the 010203 that was printed inside the foreach loop.

$row is still accessible and set to 03 because on the last iteration of the foreach loop, $row is set to the last element returned from $query->result(). If you would like to "clean it up", unset() it.

foreach ($query->result() as $row)
{
    echo $row->db_item;
}
unset($row);
Sign up to request clarification or add additional context in comments.

7 Comments

And after the foreach loop still pointing to the last key of the array, that's why shows you 03 :)
Thanks, but what if I would want to use one of the rows, let's say 02?
You'd either cancel the foreach loop on 02 by using break; (you cant 'resume' the loop though) or set some outside variable to 02 on your way through the loop.
How would I go about setting a variable on each row, $first_row == $row[0], something like this?
$query->result() returns an array. Just do $results = $query->result(). and you'll have $results[0], etc
|

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.