How can I add mysqli result set to another array

Am trying to put mysqli result set into an array for later use and this is how I did it(but is not working)

$split = [];
   $sql_money = "SELECT j_id, amount_invested FROM j_members WHERE j_activated = 1 LIMIT 5";
   $result_money = mysqli_query($conn, $sql_money);
   while($data = mysqli_fetch_assoc($result_money)){
       $split[] = ['id' => $data['j_id'], 'invest' => $data['amount_invested']];
      //echo $data['j_id'];
   }
   
   foreach($split as $s){
       echo $s['id'] . '<br>';
   }

Who can put me through

What is it doing that it should not, or not doing that it should?

You don’t actually retrieve a column called id in your query, so that won’t help.

1 Like

Like @droopsnoot says, you’re selecting j_id, not id so that should do nothing but error out

I’m not sure what the point is of copying the content of one array to to another.
Where you say $data = mysqli_fetch_assoc($result_money) then $data is already an array.

So you could forget the while and just say $split = mysqli_fetch_assoc($result_money) which is the same thing with a different variable name.
OK, you do change the key names, but that could be done in the query using AS:-

$sql_money = "SELECT j_id AS id, amount_invested AS invest FROM j_members WHERE j_activated = 1 LIMIT 5";
2 Likes

Or $split[] = mysqli_fetch_assoc($result_money);

Or is there an equivalent to PDO fetchAll()? I think there is in some mysqli implementations.

http://php.net/manual/en/mysqli-result.fetch-all.php

Thanks. Not sure if it’s still a problem now, as the OP has edited the code to use the results retrieved from the query, but not added any detail on what is actually going wrong.

Yes is now working but I prefer this which @SamA74 wrote. Short and succinct

$split[] = mysqli_fetch_assoc($result_money);

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.