keewee279
keewee279

Reputation: 1654

PHP: How to push Select results to multi-dimensional array (partially working)

I am new to PHP and hope someone can help me with this.

I have a Select query that returns (among others) the values from two columns in a db table, "ID" and "en". When getting the results from the Select I would like to store both these values for each item in a two dimensional array.

So far I have the below. The Select itself works correct but when pushing to the array it only outputs the last item from the Select results (for which it looks correct as well) so my guess is instead of adding each item to the array I am overwriting it every time.

Can someone tell me what I am doing wrong here ? Also, please let me know if something other than While should be preferred here.

My PHP:

<?php     
    $tbl = "TranslationsMain";  

    $conn = new mysqli($servername, $username, $password, $dbname);
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT * FROM " . $tbl;
    $result = $conn->query($sql);   
    while($translations = $result->fetch_assoc()){
        $arr = array('ID' => $translations['ID'], 'en' => $translations['en']);
    }
    $conn->close();
    print_r($arr);
?>

Current output (tested with a small table):

Array ( [ID] => ID10 [en] => Value10 )

Expected output:

Array ( [ID] => ID1 [en] => Value1, [ID] => ID2 [en] => Value2, [ID] => ID3 [en] => Value3, ... [ID] => ID10 [en] => Value10  )

Many thanks in advance, Mike

Upvotes: 1

Views: 76

Answers (2)

AnkiiG
AnkiiG

Reputation: 3488

Replace $arr to $arr[] and then try.

Upvotes: 1

Rasclatt
Rasclatt

Reputation: 12505

You are getting this output because you are overwriting the keys in your array. You would need to save to another array (aka not 2-dimensional):

<?php     
    $tbl = "TranslationsMain";  

    $conn = new mysqli($servername, $username, $password, $dbname);
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT * FROM " . $tbl;
    $result = $conn->query($sql);   
    while($translations = $result->fetch_assoc()){

        // ***** Create a new array here ***** //
        $arr[] = array('ID' => $translations['ID'], 'en' => $translations['en']);

    }

    $conn->close();
    print_r($arr);
?>

Gives you:

Array ( 
        [0] => Array ([ID] => ID1 [en] => Value1 ),
        [1] => Array ([ID] => ID2 [en] => Value2 ),
        [2] => Array ([ID] => ID3 [en] => Value3 ),
      )

Upvotes: 1

Related Questions