Re: foreach and mysql_fetch_array problem
| From: | Bix | Date: | Tue, 03 Jun 2003 09:12:51 +0000 |
| Subject: | Re: foreach and mysql_fetch_array problem | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-149899@lists.php.net to get a copy of this message | ||
I'm fine with using while loops, use them for most of my listing work, but I
wanted to try using a foreach loop instead but it seemed not to work as
expected. For ym table generation, I need the $key to do some maths on in
order to get my table looking right. All the guts are done, but for some
reason, when usng a foreach loop, foreach (mysql_fetch_array($result) as
$key => $value) $value is not an array of the fields. Whereas with a while
loop, it works fine. Is this a problem with foreach?
If it is, i'll stick to while, but with a counter to generate a key.
"Justin French" <justin@indent.com.au> wrote in message
news:BB0233DA.28970%justin@indent.com.au...
> This is correct:
>
> while($myrow = mysql_fetch_array($result))
> {
> // ...
> }
>
> The iteration of the while loop represents one returned row from the mysql
> result, with $myrow being an array of values returned.
>
> Rather than a SELECT * query, let's look at a something where we know the
> column names:
>
> <?
> $sql = "
> SELECT first, surname, age
> FROM employee
> WHERE age >= 18
> LIMIT 50
> ";
> $result = mysql_query($sql);
> while($myrow = mysql_fetch_array($result))
> {
> echo "Name: {$myrow['first']} {$myrow['surname']}. Age:
> {$myrow['age']}<br />";
> }
> ?>
>
>
> Now, given the above code, what else do you need to do?
>
>
> Justin
>
>
>
>
> on 03/06/03 8:25 AM, Bix (php@bix.cc) wrote:
>
> > Hi all,
> >
> > I am trying to build up a table using values from a db as follows...
> >
> > mysql_select_db($db, $sql_connection);
> > $result = mysql_query("SELECT * FROM $table WHERE $query LIMIT
> > $limit",$sql_connection);
> > $output = "<table border=\"0\" cellpadding=\"0\"
> > cellspacing=\"0\"
> > width=\"370\">\n";
> > foreach(mysql_fetch_array($result) as $key => $article){
> > //stuff
> > }
> >
> > now if I use a while loop ie:
> >
> > while ($array = mysql_fetch_array($result)){
> > //stuff
> > }
> >
> > all the matched rows are processed, however with the foreach model,
$article
> > isnt an array, it is the first row all merged together.
> >
> > Any ideas?
> >
> > ;o)
> >
> >
>