Search

Tuesday, May 31, 2011

dynamic select box with jquery, php, mysql

hello friends last Saturday i was working on a Real State project and i need to build a dynamic form to submit the properties in particular state and cities. I made that dynamic form with the help of php and jquery. Here is i describe the codes one by one.
First of all we need to create a Database. And after that Create Some tables related to your project. I Create a Database name 'test' in phpmyadmin. My these codes are related to this dynamic form you can change the Database name and fields as per your requirements. After create the database create a table, in this example i create a table name 'tbl_class' with these codes :

CREATE TABLE `test`.`tbl_class` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 200 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;

then insert some data with the help of these commands :

INSERT INTO `test`.`tbl_class` (
`id` ,
`name`
)
VALUES (
NULL , '10th Class'
), (
NULL , '11th Class'
), (
NULL , '12th Class'
);

with the help of same steps create one more table named 'tbl_student' and also use same insert command to insert the data in 'tbl_student' table.

now it is the time to connect the database with the help of php.
here is an example to connect the database named 'connection.php' .

#make Connection
 $hostname = "localhost";
 $username = "root";
 $password = "";
 $dbname = "test";
 
 //Connection layer
 $conn = mysql_connect($hostname, $username, $password);
 
 //Check connection and select DATABASE
 if( $conn )
  mysql_select_db($dbname, $conn);
 else
  die("Error in Connection!");
  

now create one more file 'index.php' and create some html stuff.
for example :

Dynamic Form



include the 'connection.php' file on the top of the 'index.php', like:

include 'connection.php';

then insert the data in the select option

#insert class data from database
         $query = "select * from tbl_class";
         $result = mysql_query($query) or die("Error in Query!
".mysql_error());
         
         while($row = mysql_fetch_array( $result ))
         {
          echo "";
         }

now it is the time to use jquery for the ajax request. Create a function with jquery to make simple the ajax request.
here is the code for the ajax request function:


create a 'getStrength.php' file to get the data through ajax request.

if(isset($_REQUEST['class']))
 {
  $classID = (int)$_REQUEST['class'];
  
  $query = "select * from tbl_student where classID = '$classID'";
  $result = mysql_query( $query ) or die("Error in Strength Query!");
  
  if($classID == 0)
   echo '';
  else{
   while($row = mysql_fetch_array($result)){
   echo "";
   }
  }  
 }

the above code is for the file 'getStrength.php'. The ajax request send the data to this file and get the result through this file.
You can beautify this dynamic form with some css effects.

hopefully you will enjoy this post.

Related Posts Plugin for WordPress, Blogger...