adiprovista
adiprovista

Reputation: 39

PHP foreach database results

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

Upvotes: 1

Views: 5815

Answers (1)

castis
castis

Reputation: 8223

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);

Upvotes: 5

Related Questions