using mysql_fetch_array() for a simple query-
SELECT id, name, roll FROM student
I get->
Array (
[0] => 1
[id] => 1
[1] => sam
[name] => sam
[2] => 5
[roll] => 5
)
But, if I replace roll with 0->
SELECT id, name, 0 FROM student
It sends->
Array (
[0] => 0
[id] => 1
[1] => sam
[name] => sam
[2] => 0
)
The 'id' is giving '0'. Whereas the query works well in mysql.
is it a bug of mysql_fetch开发者_运维百科_array?
It is not a bug. The array value with key as 0
is being overwritten.
Since you've not specified any alias for the column with constant value 0
its column name will be 0
. And this column name when it becomes the key in the array will overwrite the array the already existing value with key 0
.
[0] => 1 // for id
[id] => 1
[1] => sam // for name
[name] => sam
[0] => 0 // for 0 .. THIS WILL OVERWRITE.
Easiest way to fix this is to provide a column alias as:
SELECT id, name, 0 AS FOO FROM student
mysql_fetch_array takes two arguments. You signal with the second one how you want to get your results.
MYSQL_ASSOC
will give you an associative array with field names (or even 0
if you decide to use it as a field name). You will get:
Array ( [id] => 1 [name] => sam [roll] => 5 )
MYSQL_NUM
will give the resulting rows indexed with numbers, in the order you asked for them. You will get:
Array ( [0] => 1 [1] => sam [2] => 5 )
MYSQL_BOTH
is the default, it will populate your array both ways and can complicate things like this.
You should use mysql_fetch_assoc
instead.
Another solution is to change your query to:
SELECT id, name, 0 AS zero FROM student
精彩评论