tags:

views:

48

answers:

3

Hi

Here is a line of my code

while($row = mysql_fetch_array($result))

I want to get how many columns are in the row. I tried count($row) but this returned what I think is the number of cells for the whole $results.

i.e there are actually 7 columns, and 2 rows and count($row) returned 14. I want a function that will return 7.

Can you see where I'm going wrong.

Thanks in advance.

EDIT - Answer found

Passed MYSQL_NUM as a second parameter to mysql_fetch_array.
Thanks anyway to everyone's answers.

+2  A: 

PHP has a function that returns the number of columns:

mysql_num_fields($result)

As the other answers say, you're getting double the count because mysql_fetch_array() returns both associative keys (by column name) and numeric keys. I'd use the above function instead though, regardless of what I'm using to fetch my rows.

BoltClock
+2  A: 

mysql_fetch_array() returns the row as a combined array of numeric indexes and associative keys. Which is why you get 14 instead of 7.

Use mysql_fetch_row() instead to get just the next row as a numeric index. Or mysql_fetch_assoc() to get it with associative keys. Changing to either one will cause count($row) to return 7.

Edit I originally said mysql_fetch_array() returns the entire result. I have corrected this. The point still stands: using one of the other functions I mentioned will fix the issue.

Cfreak
That's not correct... mysql_fetch_array() will "Fetch a result row as an associative array, a numeric array, or both". It returns one row, but by default returns the columns indexed both by number as well as by column name, so each column is listed twice.
Josh
Will you forgive me if I upvote your edited answer and cause you to lose the coveted 1337-rep mark?
BoltClock
@BoltClock: LOL, no go ahead. I'll strive for 31337 :)
Cfreak
Sure, all is forgiven and I have changed my -1 to a +1 `:-)`
Josh
+2  A: 

When you use mysql_fetch_array each row has the columns indexed twice, once by column number and once by column name. So count($row) will be twice the number of columns.

Use mysql_fetch_row if you only want numerical indices, and mysql_fetch_assoc if you want name indices. These functions will both return rows with 7 entries.

John Kugelman