You are here: Re: newbie: problem with mysql_fetch_array « PHP Programming Language « IT news, forums, messages
Re: newbie: problem with mysql_fetch_array

Posted by Kimmo Laine on 06/09/06 10:15

"deko" <deko@nospam.com> wrote in message
news:z9GdnfrSOttB3hTZnZ2dnUVZ_vednZ2d@comcast.com...
> I'm trying to select a few rows:
>
> $db = mysql_connect('localhost','userID','passwd');
> if ($db)
> {
> $sql = "select cat_ID, cat_name from categories where category_count >
> 0";
> mysql_select_db('dbName');
> $result = mysql_query($sql);
> $arrayCat = mysql_fetch_array($result);
> }
> mysql_close;
>
> echo count($arrayCat); //count = 4
>
> foreach ($arrayCat as $cat)
> {
> // this will iterate 4 times
> echo "<br>".$arrayCat["cat_ID"]; // = 1
> echo "<br>".$arrayCat["cat_name"]; // = test
> }
>
> what I don't understand is I get an array count of 4, but if I look in the
> table, I see only 3 rows that meet the select criteria. Furthermore, why
> does each iteration echo the same thing:
>
> 1
> test
> 1
> test
> 1
> test
> 1
> test
>
> Am I using mysql_fetch_array wrong?
>


Yes. mysql_fetch_array only fetches one row from the result. In this case it
fetches an array that looks something like
array {
0 => 1
cat_ID => 1
1 => test
cat_name => test
}

It has both numerical and textual indexes. So these are the four elements
you get in the loop. You can test this with print_r($arrayCat);

Instead of fetching just one row and iterating it's fields, you should fetch
rows as long as they keep coming.
instead of the foreach you had there, try something like this:

while($cat = mysql_fetch_array($result)){
echo "<br>".$cat["cat_ID"]; // = 1
echo "<br>".$cat["cat_name"]; // = test
}

--
"ohjelmoija on organismi joka muuttaa kofeiinia koodiksi" -lpk
spam@outolempi.net | Gedoon-S @ IRCnet | rot13(xvzzb@bhgbyrzcv.arg)

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация