简体   繁体   中英

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, eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM