Skip to content Skip to sidebar Skip to footer

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 serve

Solution 1:

You should try it like this:

<?php

mysql_select_db("$db_name") ordie(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>';

?>

Solution 2:

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>";
}

Solution 3:

mysql_select_db("$db_name") ordie(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;
}

Solution 4:

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.

Post a Comment for "Populating Dropdown With Query Results In Php"