Forum Moderators: coopster

Message Too Old, No Replies

mysql_query gets each field twice

Each field gets two indexes

         

MatthewHSE

1:10 pm on Apr 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here's the code:

$Query = mysql_fetch_array(mysql_query("SELECT * FROM Table WHERE Color='Blue'"));
foreach ($Query as $k => $v) { echo "<b>$k:</b> $v<br>"; }

The query is returning a single row from the table (which is what I intended). The output is as follows:

0: Widget
Product: Widget
1: Blue
Color: Blue
2: 9.95
Price: 9.95

...where (obviously) Product, Color and Price are the table fields.

I have a feeling my problem comes down to a misunderstanding of how arrays are supposed to work, or at least how they're supposed to work in this instance. Nevertheless, I'm confused - why is a numeric index assigned at all?

whoisgregg

1:30 pm on Apr 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Some times you want numbers, sometimes you want the fieldnames, sometimes you want both. So the function mysql_fetch_array() lets you choose. What's confusing is the default value. :)

From the manual: [php.net]

mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both

array mysql_fetch_array ( resource result [, int result_type] )

result_type
The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH

dreamcatcher

1:32 pm on Apr 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can just use mysql_fetch_assoc.

dc

MatthewHSE

2:18 pm on Apr 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks guys. Wouldn't you know it, the times I forget to check the manual are always the times it has the simplest answers! ;)