niko
niko

Reputation: 9393

why does count return 22 instead of 11?

This is my php script

$result = mysql_query("SELECT * FROM photos WHERE perID=2");
$row = mysql_fetch_array($result);
$a = count($row);                     // or sizeof($row)
echo $a;       //outputs 22 but i expect it to be 11 but why does it output 22 ?

This is the data in mysql.

perID   one    two   three   four    five    six    sev    eit   nine  ten
  2    1.jpg  2.jpg  3.jpg   4.jpg   5.jpg  6.jpg  7.jpg  8.jpg  9.jpg 10.jpg

I expect it to be 11 but surprisingly its 22. Could anyone explain me why? Does it also include the 'one' 'two' (the column names) stuff too in the count function ? because it would be 22, if only if it includes them.

But it should not include the column part of table as they are headers right? please help me with these Any help is greatly appreciated

also please give me a link or the way to achieve 11 as result

Upvotes: 0

Views: 90

Answers (5)

middus
middus

Reputation: 9121

If you use mysql_fetch_assoc(), you'll only have $row['one'] and no more $row[1].

Upvotes: 0

Rene Pot
Rene Pot

Reputation: 24815

mysql_fetch_array returns 2 colums per column.

For example:

array(
    [0] => '1.jpg',
    ['one'] => '1.jpg'
    etc..

if you do mysql_query($query,MYSQL_ASSOC) you will get the ['one'] only.

Check this documentation: https://www.php.net/manual/en/function.mysql-fetch-array.php

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157915

a magic link: http://php.net/mysql_fetch_array

your table setup doesn't seem quite sensible, by the way.

Upvotes: 0

hsz
hsz

Reputation: 152286

If you look into documentation of mysql_fetch_array, you will see a second parameter:

$result_type = MYSQL_BOTH

It means that, function returns merged arrays with associative keys and numeric keys too.

So you have doubled data.

You can avoid it with:

$row = mysql_fetch_array($result, MYSQL_ASSOC);

or just:

$row = mysql_fetch_assoc($result);

Upvotes: 0

Marc B
Marc B

Reputation: 360772

mysql_fetch_array() by default returns a combined associative AND indexed array structure.

SELECT a,b,c FROM table

will produce a row array of

$row = array(0 => 'value of a', 'a' => 'value of a', 1 => 'value of b', etc...);

You can force it to do one or the other by specifying the optional fetch_mode parameter:

$row = mysql_fetch_array($result, MYSQL_BOTH); // default mode
$row = mysql_fetch_array($result, MYSQL_ASSOC); // same as mysql_fetch_assoc: associative array
$row = mysql_fetch_array($result, MYSQL_NUM); // same as mysql_fetch_row: indexed array

Upvotes: 7

Related Questions