Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop mysql_fetch_assoc using foreach instead of a while loop [closed]

Tags:

php

I have a mysql query:

$result = mysql_query("my query");

Is there a way to make something like this work?

$results = mysql_fetch_assoc($result); // fetch the results

And loop them using foreach instead of the classic while:

foreach($results as $result){
   $result1 = $result->result1;
   $result2 = $result->result2;
}

Ty

like image 305
webmasters Avatar asked Jan 16 '23 00:01

webmasters


1 Answers

Foreach is a construct that iterates arrays and objects. mysql_fetch_assoc will return an array but each array will be only one row's worth of data. So your foreach will simply be giving you the columns present in the first row.

Save yourself from trouble, don't use mysql_fetch_assoc and foreach together.

like image 149
Kalpesh Avatar answered Feb 19 '23 15:02

Kalpesh