From this simple query, I could not figure out why I am getting the repeated result one in [0] and another in [m_id]. I believe the result from given query must display only two values.
$sql="SELECT m.m_id, m.work FROM mun as m WHERE m.mun_id=7 ";
$rslt=mysql_query($sql);
$result=mysql_fetch_array($rslt);
print_r($result);
Output:
Array
(
[0] => 7
[m_id] => 7
[1] => 260
[work] => 260
)
Can somebody figure me out what I am doing wrong. Thank you.
That's the normal behavior of mysql_fetch_array
. It provides both numerical and associative indices.
If you want only one of them, use mysql_fetch_assoc
or mysql_fetch_row
$result=mysql_fetch_row($rslt);
Array
(
[0] => 7
[1] => 260
)
or
$result=mysql_fetch_assoc($rslt);
Array
(
[m_id] => 7
[work] => 260
)
It's also worth mentioning that you can get this behavior using mysql_fetch_array
by passing a second argument.
// same as mysql_fetch_row
$result=mysql_fetch_array($rslt, MYSQL_NUM);
and
// same as mysql_fetch_assoc
$result=mysql_fetch_array($rslt, MYSQL_ASSOC);
More info: http://php.net/manual/en/function.mysql-fetch-array.php
The description of mysql_fetch_array
is the following:
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
where the second optional parameter is:
The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
And about return value:
The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
It is cited from http://php.net/manual/en/function.mysql-fetch-array.php.
So, in your case, default MYSQL_BOTH
was applied. I'm sure that the following must solve:
$result=mysql_fetch_array($rslt, MYSQL_ASSOC);
or
$result=mysql_fetch_array($rslt, MYSQL_NUM)
;