Form Elements : PHP Creating Dynamic Drop Down

In this blog post, tried to expalin the method of loading data from the database to the Drop Down which is a static html form element.

Before doing this, let's understand how a typical Drop Down form element works.


<select name="test">
 <option value="Manager 1"> Manager 01</option>
 <option value="Manager 2"> Manager 02</option>
</select>



So, to load dynamically data to the dropdown you need to output these tags as PHP echo statements to the web page.


First, lets's create a proper database called 'test' and in it create a table called 'example'. Here's the MySQL script to do that,


create database test;


create table example
(
  name varchar(200) not null  
);

insert into example values('Harsha');

insert into example values('Danika');



After executing the above MySQL Script, you may need to proceed with the PHP Coding.


Here's the Database Configuration PHP Code which should be included in the Project Directory of the Current Project that we're working on and later should be included in the PHP code itself with PHP 'include()' . Name it as db_conn.php.

<?php

 $host = "127.0.0.1";
 $username = "root";
 $pword = "";
 $db_name = "test";
 
 
 mysql_connect( $host , $username , $pword ) or die(mysql_error());
 mysql_select_db($db_name) or die(mysql_error());
 
?>

Here's the PHP Code in the index.php file in order to perform the required task.


<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title></title> 
</head> 
<body> 
<form name="form">

This is the Static Form Element 

<select name="test_static"> 

       <option value="Manager 1"> Manager 01</option>

       <option value="Manager 2">Manager 02</option> 

</select>
<br/> 
This is the Dynamic Form Element 

<select name="test_dynamic"> 

<?php 

      include('db_conn.php'); 

      $query = "SELECT name FROM example"; 

      $result = mysql_query($query); 

      while($row= mysql_fetch_array($result)) 
      {
          echo '<option value="'.$row['name'].'">';
          echo $row['name'];
          echo '</option>'; 
      }  
?> </select> </form> </body> </html>

No comments: