0

I am trying to fetch data from MySQL. Because I am still learning PHP and MySQLi, I do not completely understand why this code prints double results with numeric keys too. I need push only string keys with values. Thanks for some direction.

code

if ( $r = $mysqli -> query ( $q ) ) {
    ${ 'err_css_' . $err_asid } = array ();
    while ( $row = mysqli_fetch_array ( $r ) ) {
        array_push ( ${ 'err_css_' . $err_asid }, ${ 'err_css_' . $err_asid }[$row['language_asid']]=$row['value'] );

    }
    print_r ( ${'err_css_' . $err_asid } );
}

result:

Array (
  [ces] => background:czech_flag_url;
  [0] => background:czech_flag_url; // i dont want numeric key
  [eng] => background:english_flag_url;
  [1] => background:english_flag_url; // i dont want numeric key
)
5
  • fetch_array populates both numeric and string keys, you're looking for fetch_assoc. Commented Sep 22, 2014 at 10:09
  • @georg If I change it to while ( $row = mysqli_fetch_assoc ( $r ) ), the result is same. Commented Sep 22, 2014 at 10:11
  • why this code prints double results with numeric keys too this is by default, otherwise you need to pass additional flags in fetch_array for what you really want. Commented Sep 22, 2014 at 10:14
  • Yes, right, the problem is with array_push, not fetch_array. Remove array_push, and simply write $array[$row['language_asid']] = $row['value'] Commented Sep 22, 2014 at 10:15
  • @georg Thank you very much :) That was my target, make the answer if you want. I will accept. Commented Sep 22, 2014 at 10:18

3 Answers 3

2

The problem is that you're using array_push incorrectly. Actually, you don't need it at all:

if ( $r = $mysqli->query ( $q ) ) {
    $css = array ();
    while ( $row = mysqli_fetch_array ( $r ) ) {
        $css[$row['language_asid']] = $row['value'] );
    }
}

Also, I'd suggest that you don't use "variable variables". This is an essentially useless feature, that does nothing but reduce readability of your code. Use arrays or objects:

${ 'err_css_' . $err_asid } = array (); // NO

$err_css[$err_asid] = array ();         // yes
0
1

Instead of using mysqli_fetch_array You need to use mysqli_fetch_assoc

0

The reason it is showing double results is because there is double results! mysqli_fetch_array() produces both associative and numerical arrays with identical values. Consider either using mysqli_fetch_assoc() or using is_numeric($key) to filter the results further.

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.