user2712167
user2712167

Reputation: 1

Populating dropdown with query results in PHP

The code should open all the rows of gamename column of games table and put 1700 rows into drop down menu, but it only displays a blank dropdown with 1700 rows.

// Connect to server and select database.
mysql_connect("$host", "$username", "$password") or die(mysql_error());

mysql_select_db("$db_name") or die(mysql_error());
$i=0;
$result = mysql_query("SELECT gamename FROM games");
$storeArray = Array();
echo '<select name="game" style="width: 400px">';

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
      $storeArray[] =  $row[i];  

     echo "<option>".$storeArray[i]."</option>";
     $i= $i+1;
}

?>
</select>

Upvotes: 0

Views: 3216

Answers (4)

wiscWeb
wiscWeb

Reputation: 213

You have more than one issue here... But give this a try. (Also I would start to use PDO or mysqli if I were you...)

$result = mysql_query("SELECT gameid, gamename FROM games");
//$storeArray = Array();
echo '<select name="game" style="width: 400px">';

while ($row = mysql_fetch_assoc($result)) {
$gamename =  $row['gamename'];  
$gameid = $row['gameid'];
echo "<option'".$gameID."'>".$gamename."</option>";
}
echo '</select>';

This is assuming you have an ID field in your games table. You weren't assigning the options any value. Which won't be useful. Also you weren't pulling the data in the way you had it.

Upvotes: 0

albertdiones
albertdiones

Reputation: 733

mysql_select_db("$db_name") or die(mysql_error());
$i=0;
$result = mysql_query("SELECT gamename FROM games");
$storeArray = Array();
echo '<select name="game" style="width: 400px">';

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] =  $row['gamename'];  

echo "<option>".$storeArray['gamename']."</option>";
$i= $i+1;
}

Upvotes: 0

MonkeyZeus
MonkeyZeus

Reputation: 20737

You should try it like this:

<?php

mysql_select_db("$db_name") or die(mysql_error());

$sql = "SELECT gamename FROM games";
$query = mysql_query($sql);

echo '<select name="game" style="width: 400px">';
while ($row = mysql_fetch_assoc($query)) {
    echo '<option>'.$row['gamename'].'</option>';
}
echo '</select>';

?>

Upvotes: 2

andrewsi
andrewsi

Reputation: 10732

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row[i];  

    echo "<option>".$storeArray[i]."</option>";
    $i= $i+1;
}

For one thing, you're using i and $i interchangeably here; this may or may not cause an issue. You're assigning the ith member of $row into $storeArray, and that's not going to work after the first row, as there's only one item in your SELECT.

Why not just do:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "<option>".$row['gamename']."</option>";
}

Upvotes: 1

Related Questions