Roddeh
Roddeh

Reputation: 207

Storing php query result into an array

I know this probably will be silly, but I'm getting frustrated not finding the solution. Here I go: I have a table which contains players, I would like to store the players into an array in a form like this:

Array ( [0] => player1 [1] => player2 [2] => player3)

now what I get from my code below is this:

Array ( [0] => Array ( [player] => player1 ) [1] => Array ( [player] => player2 ) [2] =>   Array ( [player] => player3 )) 

So I get this extra layer into my array called 'player' which is the name of the column field I'm selecting from. How do I adjust my code?

$query_players="SELECT player FROM `whiteboard_games` WHERE id='$id'";
$result = mysql_query($query_players) or die;
$players = array();
while($row = mysql_fetch_assoc($result))
{ $players[] = $row; }

Thanks a lot!

Upvotes: 3

Views: 9766

Answers (3)

Ankur Saxena
Ankur Saxena

Reputation: 639

$players = array();
while($row = mysql_fetch_assoc($result)) 
{ 
  $players[] = $row['player'];
} 
echo "<pre>";
print_r($players);

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270607

There are many ways to handle this. If you have only the one column, rather than appending the whole $row, the most straightforward is to just append the column you want:

while($row = mysql_fetch_assoc($result))
{
  // Append only the `player` column rather than the whole $row (which is an array)
  $players[] = $row['player'];
}
var_dump($players);

If you had the multidimensional array already and needed to flatten it, you can do so with a loop;

$players_flattened = array();
foreach ($players as $p) {
  $players_flattened[] = $p['player'];
}
// Or via array_map()
$players_flattened = array_map(function($p){ return $p['player']; }, $players);

Note: We assume you have already filtered and validated $id in your query, to protect against SQL injection.

Upvotes: 6

Teena Thomas
Teena Thomas

Reputation: 5239

Add only values of the key player to the array $players,

 while($row = mysql_fetch_assoc($result)) {
   $players[] = $row['player']; 
}

Upvotes: 1

Related Questions