Populating dropdown with query results in PHP

时间秒杀一切 提交于 2019-12-11 19:33:38

问题


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>

回答1:


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>';

?>



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



回答3:


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



回答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.



来源:https://stackoverflow.com/questions/18410276/populating-dropdown-with-query-results-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!