Search code examples
phpmysqlsqlforeachresultset

foreach on resultset mysql return only one value randomic


I am trying do some simple select in one script.

I see if I try to read my resultset with a while there isn't any problem but if I try to use foreach, I just read 1 o 2 value all wrong... why?

$sql = " select * from tutorials_tbl";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);  
 }


 $sql = " select * from tutorials_tbl";
            $result = mysql_query($sql);
    foreach($rows= mysql_fetch_array($result, MYSQL_BOTH) as $row) {
     printf("ID: %s  Name: %s", $row[0], $row[1]);  
    }   

-

* OUTPUT WHILE*

ID: 0 Name: title0
ID: 1 Name: title1

ecc....

*OUTPUT FOREACH*

 ID: 1 Name: 
 ID: 1 Name: 
 ID: t Name: i
 ID: t Name: i 

Solution

  • The reason you are only getting one row with foreach is that the function mysql_fetch_array() only returns a single record.

    In the while loop the condition where the function is called is re-evaluated on every loop. This is perfect.

    The foreach you have is quite strange and I'm thinking what happens is that mysql_fetch_array() reads one record as an array into the variable $rows, and then it would iterate over each COLUMN in the record.... in other words $rows is just one row, and $row is one value in the row. The reason you only see one or two letters in the output is because $row[0] on a string just gives you the 0th letter in the string.

    The only way the foreach would work is with a 'fetch all' function which gives an array of arrays. But you'd have to create that yourself... it would probably mainly contain the while loop :)

    If you use PDO as suggested it comes with fetchAll capabilities.