1

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.

2
  • 4
    a) don't use mysql - it's been deprecated and in PHP7 removed. use mysqli or PDO instead. b) you're not doing something wrong, you're just getting associative and numeric indizes. the fix is using mysql_fetch_assoc instead - but again: switch to mysqli or PDO Commented Feb 22, 2017 at 8:28
  • Yeah thank you for suggestion. Commented Feb 22, 2017 at 8:31

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.