Become Our Fan on Social Sites!

Facebook Twitter

Google+ RSS YouTube

Saturday 10 May 2014

Populate Select Box / Drop Down Dynamically From Database

How to fill select box dynamically from database table. Here is a tutorial of how to fill up HTML drop down menu dynamically from MySQL database table.
Fill or Populate Drop Down or Select Box Dynamically Using Database
Fill Select Box / Drop Down Dynamically

You should have little knowledge about how to execute different SQL query in PHP. If you have any doubt about PHP database connection with MySQL then you should like following tutorial:

"PHP Database Connection With MySQL".

You should also have knowledge about select box / drop down menu. If you have doubt then click on the following link for drop down menu tutorial:

"Create Drop Down Menu / Select Box In HTML"

Let's start our tutorial of "how to fill up select box dynamically".

Create one database named "db_demo" in MySQL. Then create table in it named "tbl_city". To create table in database use following SQL query:

CREATE TABLE `db_demo`.`tbl_city` (
`id` INT NOT NULL AUTO_INCREMENT ,
`city_name` VARCHAR( 30 ) NOT NULL ,
PRIMARY KEY ( `id` )
)

Now insert some data in the "tbl_city" table using following query:

INSERT INTO `db_demo`.`tbl_city` (
`id` ,
`city_name`
)
VALUES (
   NULL , 'Ahmedabad'
   ), (
   NULL , 'Rajkot'
   ), (
   NULL , 'Mumbai'
   ), (
   NULL , 'New Delhi'
   ), (
   NULL , 'Chennai'
  );

After creating database, table and inserting data to the table, then create one PHP file and write following code in the file and execute file. You are done, select box / HTML drop down menu filled with city name dynamically from database table.

Source Code:
<form>
  <strong>Select City: </strong>
  <select>
  <?php
     $connection = mysql_connect('localhost','root','');
     mysql_select_db('db_demo', $connection);
     $query = "select city_name from tbl_city order by city_name asc";
     $result = mysql_query($query);
     while( $rs = mysql_fetch_array($result) )
     {
      echo '<option value="'.$rs['id'].'">'.$rs['city_name'].'</option>';
     }
  ?>
  </select>
</form>


OUTPUT:


Select City:


Above source code contains PHP-MySQL database query and HTML select box creation codes. Select box / drop down menu filled with city name in ascending order by using 'order by' clause of SQL - Structured Query Language. Using dynamic select box / drop down menu reduces lines of code and it is easy to manage.

If you have any query then please comment below

0 comments :

Post a Comment