Site Loader
Get a Quote

Dynamic dropdown in PHP using MySQL and jQuery:


Dynamic dropdown in PHP:   Hi readers, today we begin with the new topic “ Dynamic dropdown in PHP ” which is generally used in the form to select from the given list of items like select country, state, city, categories, etc. Here in this tutorial, we will explain the details of how we can populate data from MySQL to the drop-down list of HTML forms using jQuery and PHP. Later on, we provide the full source code with snapshot view which makes this concept more clear and concise. In fact at the end of this tutorial, we will provide the zip folder to download the full source code.

Let’s begin the tutorial on Dynamic dropdown in PHP !

Simple Example of Dynamic Dropdown in PHP using MySQL & jQuery : (Step-by-Step Guide)


Step1: First, Create a Database and table directly from the PHPMyAdmin 

open localhost/phpmyadmin and open sql tab and run the below sql query command

Create Database dropdown;

CREATE TABLE IF NOT EXISTS state (
  id int(11) NOT NULL AUTO_INCREMENT,
  state varchar(50) NOT NULL,
  cid int(11) NOT NULL,
 PRIMARY KEY (id)
 );

 


Step 2 : After table creation create a HTML Form containing dropdown menu using PHP script.

Here in this index.php file, there is simply one dropdown menu to select items from the list of a number of items. So copy the code below and then save it with name index.php.

index.php


<!DOCTYPE html>
<html>
<head><title>Loading MySQL Records in DropDown List using PHP and jQuery</title>
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/drop.js"></script>
</head>
<body> 
     <form name="frmdropdown">
     <center> 
     <h2 align="center">Select data</h2> 
      <strong> Select State: </strong>
      <select name="state" id="state">   
         <option value="select" selected="selected">--SELECT--</option>  
      </select>      
      <input type="submit" name="submit" value="submit" />
      </center>
      </form>
  <blockquote>Load MySQL Records On Drop Down Selection</blockquote>
    <hr />
</body>
</html>


 

Step 3: Create a .js file to use jQuery and Ajax code

Here in this JavaScript file, firstly we have to make the function named “state()” under which we have used ajax function to populate data from Mysql in a dropdown list without page refresh. Later on, call that function when the document is loaded.

Note:

In the beginning, we have to use the below code to empty all the records of dropdown with id=” state”.

 //remove all existing options
  $("#state").empty();

drop.js


//function to load data in dropdown
 function state(){
$('#state').empty(); //remove all existing options

//ajax function is called 
$.ajax
 ({
 type: 'POST',
 url: 'dropdown1.php',
 dataType: 'text',
 cache: false,
 success: function(data){
 $('#state').html(data);
 },
 complete: function(){}
 }); 
 }
//main javascript code
$(document).ready(function(){
 state();
 });

 

Step 4: Create a PHP file to write a script to populate records from MySQL to dropdown list.

Here in this step first we create two files named db.php and dropdown.php . Copy the below code and then save it one by one.

In the db.php file, we simply create and check connection with MySQLi or we can say that it is a configuration file.

Whereas dropdown.php file is used to run the SELECT query to search all records of table state of database dropdown using MySQL procedural function. Also, fetch the result and display records in dropdown option each time using while loop as shown below:

 $output.='<option value="'.$rows["id"].'">'.$rows["state"].'</option>';

db.php


<?php

// Login Credentials
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dropdown";
 
//Create a Connection
$conn=mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
 
// Check Connection
if(!$conn){
  die("connection does not establish,error: ". mysqli_connect_error());
}

?>

dropdown.php


<?php
require_once 'db.php';

//new variable
$output='';

//SELECT query
$sql="select DISTINCT state from state";

$output.='<option value="">SELECT STATE--</option>';
//run the above query
$display=mysqli_query($conn,$sql);

//display records
if(mysqli_num_rows($display))
{ 
while($rows=mysqli_fetch_assoc($display))
{ 
 $output.='<option value="'.$rows["id"].'">'.$rows["state"].'</option>';
 } 
 echo $output;
 }
//close the connection
mysqli_close($conn);

?>


Snapshot view of Dynamic dropdown in PHP using MySQL and jQuery :

Dynamic dropdown in PhP
Dynamic dropdown in PhP

Download file:   dynamic.zip

 

I hope you would like this tutorial on how we can make Dynamic dropdown in PhP using MySQL and jQuery !

Post Author: TechieFlair

Leave a Reply

Your email address will not be published.