Populate dropdown menu from MySQL database?

I would like to create a dropdown menu in PHP that loops through a MySQL database table of names. The dropdown will just display the name and the user can select the name for form submission. Each name in the table also has a unique id. Im totally lost on this one… Any help would be great! Thanks

Do you know how to get a result set from a SELECT query from MySQL?
The markup you’re aiming for will look a bit like this:


<select name="cities">
  <option value="12">New York</option>
  <option value="31">Singapore</option>
  <option value="44">Bejing</option>
</select>

HI you can do this way


//db connection
mysql_connect("localhost","user","password");
mysql_select_db("database");

//query
$sql=mysql_query("SELECT id,name FROM table");
if(mysql_num_rows($sql)){
$select= '<select name="select">';
while($rs=mysql_fetch_array($sql)){
      $select.='<option value="'.$rs['id'].'">'.$rs['name'].'</option>';
  }
}
$select.='</select>';
echo $select;

Thanks!

Actually that did not work

elaborate Airludy, did you get errors? No output? what?

Just did this today actually lol. It’s in OO if you are familiar


<?php

$conn = new mysqli('localhost', 'username', 'password', 'database') 
or die ('Cannot connect to db');

    $result = $conn->query("select id, name from table");
    
    echo "<html>";
    echo "<body>";
    echo "<select name='id'>";

    while ($row = $result->fetch_assoc()) {

                  unset($id, $name);
                  $id = $row['id'];
                  $name = $row['name']; 
                  echo '<option value="'.$id.'">'.$name.'</option>';
                 
}

    echo "</select>";
    echo "</body>";
    echo "</html>";
?>

Or you can make it into a function and place it in the middle of html code and get rid of that echo <html>, <body> and all that
Hope this helps!

1 Like

I managed to make work to me … Here’s the code I found today (and a little modified) - AT THE END of all this I’ll put a simple question (I cannot find the answer on PHP Manual or in other places …)


A database with 2 tables (I didn’t like at all that the name of the second field is exactly the name of the table … but that is what I found …)

Database

CREATE TABLE category ( cat_id int(2) NOT NULL auto_increment, category varchar(25) NOT NULL default '', PRIMARY KEY (cat_id) ) TYPE=MyISAM;


INSERT INTO category VALUES (1, 'Fruits'); INSERT INTO category VALUES (2, 'Colors'); INSERT INTO category VALUES (3, 'Games'); INSERT INTO category VALUES (4, 'Vehicles');


 # -------------------------------------------------------- # # 
 # -------------------------------------------------------- # # 
 # -------------------------------------------------------- # # 

Table structure for table `subcategory` # 

CREATE TABLE subcategory ( cat_id int(2) NOT NULL default '0', subcategory varchar(25) NOT NULL default '' ) TYPE=MyISAM; 
# # Dumping data for table `subcategory` # 

INSERT INTO subcategory VALUES (1, 'Mango'); INSERT INTO subcategory VALUES (1, 'Banana'); INSERT INTO subcategory VALUES (1, 'Orange'); INSERT INTO subcategory VALUES (1, 'Apple'); INSERT INTO subcategory VALUES (2, 'Red'); INSERT INTO subcategory VALUES (2, 'Blue'); INSERT INTO subcategory VALUES (2, 'Green'); INSERT INTO subcategory VALUES (2, 'Yellow'); INSERT INTO subcategory VALUES (3, 'Cricket'); INSERT INTO subcategory VALUES (3, 'Football'); INSERT INTO subcategory VALUES (3, 'Baseball'); INSERT INTO subcategory VALUES (3, 'Tennis'); INSERT INTO subcategory VALUES (4, 'Cars'); INSERT INTO subcategory VALUES (4, 'Trucks'); INSERT INTO subcategory VALUES (4, 'Blkes'); INSERT INTO subcategory VALUES (4, 'Train'); 

index.php file


&lt;?php

# Connection 
// I define constants (but I would prefer to put this start of the page, with 
//this php code, somewhere else, as I have read, you know, for security
//... but where to put it on the server and then include it ?...)

DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'mysqlhost(server)');
DEFINE ('DB_NAME', 'databasename');

// Connection with MySQL server

$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Cannot connect to MySQL server: '.mysql_error());

// Select database

@mysql_select_db (DB_NAME) OR die ('Cannot select database: '.mysql_error());

echo " YEAP, it did connect !!! ";

?&gt;

&lt;html lang="en-en" &gt;

&lt;head&gt;
&lt;title&gt;2 Dropdown lists - populated from MySQL database&lt;/title&gt;

&lt;SCRIPT language=JavaScript&gt;
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='index.php?cat=' + val ;
}
&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;

&lt;?php

@$cat=$_GET['cat']; // Use this line or below line if register_global is off

if(strlen($cat) &gt; 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not. 
echo "Data Error";
exit;
}


@$cat=$HTTP_GET_VARS['cat']; // Use this line or above line if register_global is off



///////// Getting the data from Mysql table for first list box//////////
$quer2 = mysql_query("SELECT DISTINCT category,cat_id FROM category ORDER BY category");
///////////// End of query for first list box////////////

/////// for second drop down list we will check if category is selected else we will display all the subcategory/////
if(isset($cat) and strlen($cat) &gt; 0){
$quer = mysql_query("SELECT DISTINCT subcategory FROM subcategory WHERE cat_id=$cat ORDER BY subcategory"); 
}
else{$quer = mysql_query("SELECT DISTINCT subcategory FROM subcategory ORDER BY subcategory"); } 
////////// end of query for second subcategory drop down list box ///////////////////////////


echo "&lt;form method=post name=f1 action='index-check.php'&gt;";

/// Add your form processing page address to action in above line. Example  action=index-check.php////

////////////////////////////////////////////////////////

//////////  START of the FIRST drop downlist  /////////
echo "&lt;select name='cat' onchange=\\"reload(this.form)\\"&gt;&lt;option value=''&gt;Select Category&lt;/option&gt;";

while($noticia2 = mysql_fetch_array($quer2))
{ 
  if($noticia2['cat_id']==@$cat) 
    {echo "&lt;option selected value='$noticia2[cat_id]'&gt;$noticia2[category]&lt;/option&gt;"."&lt;BR&gt;";}
  else{echo  "&lt;option value='$noticia2[cat_id]'&gt;$noticia2[category]&lt;/option&gt;";}
}

echo "&lt;/select&gt;";

//////////  END the the FIRST drop down list  ///////////

?&gt;

&nbsp;&nbsp;&nbsp;

&lt;?php

////////////////////////////////////////////////////////

//////////  START of the SECOND drop downlist  /////////
echo "&lt;select name='subcat'&gt;&lt;option value=''&gt;Then select subCategory&lt;/option&gt;";

while($noticia = mysql_fetch_array($quer))
{ 
echo  "&lt;option value='$noticia[subcategory]'&gt;$noticia[subcategory]&lt;/option&gt;";
}

echo "&lt;/select&gt;";

//////////  END the the SECOND drop down list  ///////////

?&gt;

&nbsp;&nbsp;&nbsp;

&lt;?php

//// Add your other form fields as needed here/////

echo "&lt;input type=submit value=Submit&gt;";
echo "&lt;/form&gt;";

?&gt;

 
&lt;/body&gt;

&lt;/html&gt;

And the file
index-check.php



&lt;html lang="en-en" &gt;
&lt;head&gt;
&lt;title&gt;Multiple drop down lists&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;?php
$cat=$_POST['cat'];
$subcat=$_POST['subcat'];

echo "Value of \\$cat = $cat &lt;br&gt;Value of \\$subcat = $subcat ";
echo "&lt;p&gt;&lt;/p&gt;";
echo "I'm interested in  ***** (variable)";

?&gt;

&lt;/body&gt;

&lt;/html&gt;

Now :

What on Earth is NOTICIA !!!
It works, but what is NOTICIA ??!!

Thanks !

:slight_smile:

Notica? Are you getting a Notice error from PHP? If so can you post the text of the error?

Couple of things
1/ get rid of this line:

@$cat=$HTTP_GET_VARS['cat']; // Use this line or above line if register_global is off

its really not required.

2/ take the @signs off the mysql lines. It suppresses the errors that you will need in case it all goes wrong.

3/ noticia is just the simple variable assigned to hold the results of the query which are returned as an array.
You could call it anything you like just as arron did in post #7, he called it $row.


while ($row = $result->fetch_assoc()) {