PHP form dropdown containing options based on SQL

2019-08-29 02:32发布

问题:

I have a form with a dropdown field which I would like to populate with a list of bands that exist in my 'bands' database. I have tried several pieces of code, but the dropdown list is always empty. I know that the DB connection is fine because I am calling the connection in several parts of my application. Here is my attempt at the code:

<?php

$select_query= "Select bandname from bands";
$select_query_run = mysql_query($select_query);
echo "<select name='bands'>";
while ($select_query_array=   mysql_fetch_array($select_query_run) )
{
        echo "<option value='' >".htmlspecialchars($select_query_array["bandname"])."</option>";
}
echo "</select>";

?>

回答1:

First of all turn on error reporting and resolve if there is any error.

If there is no error and still no options are displayed, that means the query is not returning any result. So try to confirm it by running the query in another MySQL client and see if it actually returns any result.



回答2:

Adding mysql_select_db will resolve your issue

<?php
   // Report all PHP errors (see changelog)
   error_reporting(E_ALL);
   mysql_select_db("dbname") or die("Could not open the db");
   $select_query= "select bandname from bands";
   $select_query_run = mysql_query($select_query) or die(mysql_error();
   echo "<select name='bands'>";
    while ($select_query_array=   mysql_fetch_array($select_query_run) )
    {
        echo "<option value='' >".htmlspecialchars($select_query_array['bandname'])."</option>";
    }
    echo "</select>";
?>