SQL PHP HTML ASP JavaScript articles and free scripts to download

Creating a drop down list box using data from MySQL table

We can get the options or the list items of a drop down list box from a mysql table. Here the records we will get from the table will be used to populate the drop down list box. So the options are dynamically added to the list box, this way we get flexibility in selecting the options. Here we will first populate the list with options directly taking from the table. Then we will restrict the options by adding a WHERE Clause to the sql statement we use for retrieving the data from the table.

For example we are populating the list box with student names at the first stage. Then we will add a restriction and collect only the records of the boys from the table. This example you can extend to any other condition like displaying state list with population more than some value.

In the first stage we will learn how to get the data from MySQL table and then populate the list box. In second stage we will add restriction by using a period button to the list box. For our demo here we will use the student table and you can download / copy the SQL dump file to create your table with student data. The small PHP code we will discuss you can copy and use directly from here.

We are not discussing the connection to mysql part here and we assume connection is open for us. You can see different mysal connection strings used in different scripts here. We will start with the simple SQL select query used to collect the names and ids of the students from the table.

include "config.php"; // Database connection using PDO
//$sql="SELECT name,id FROM student";
$sql="SELECT name,id FROM student order by name";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=student value=''>Student Name</option>"; // list box select command
foreach ($dbo->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[name]</option>";
/* Option values are added by looping through the array */
} echo "</select>";// Closing of list box

The list box is here

The SQL file ( dump ) to create student table with records is here

Post Comment This is for short comments only. Use the forum for more discussions.
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked

Join Our Email List
For Email Newsletters you can trust
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer