Google search

Basic and advanced computer skills like Excel with macros, How to speed up your PC, C, CPP, Java programming, HTML, JavaScript, PHP, Wordpress, all web tools, Android tutorials, MySQL Tutorials, WAMP server installation. etc.

Fill values in combo box from MySQL using PHP

The below example shows that How to fill values in second combo box based on first combo box selected values from MySQL DB using PHP

1 Create a table called "Course" as following screen shot with insert few records as well in it.








2. Create another table called "Subjects" and add few records as following.



















3. Now create "config.php" with following code in it.
<?php
      $host="localhost";
      $username="root";
      $password="";
      $dbname="demo";
      $con=mysql_connect("$host","$username","$password");
      mysql_select_db("$dbname",$con);
?>

In the above code please enter your database name, user name, password etc. 

4. Now create "cmb5.php" program with following code in it.
<?php
include('config.php');
?>
<html>
<head>
<script language="javascript">
    function showSub(catid)
 {
 document.frm.submit();
 }
</script>
</head>
<body>
<h2> Fill values in second combo box based on </br> first 

combo box values from MySQL DB using PHP </h2>
<hr color=red>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<form action="" method="POST" name="frm" id="frm">
<table width="500" border="0">
  <tr bgcolor=silver>
    <td>Course</td>
    <td> <select name="course_id" id="course_id" 

onChange="showSub(this.value);">
       <option value="">--Select--</option>
       <?php
        $sql1="select * from course";
       $sql_row1=mysql_query($sql1);
       while($sql_res1=mysql_fetch_assoc($sql_row1))
       {
       ?>
       <option value="<?php echo $sql_res1["id"]; ?>" 

<?php if($sql_res1["id"]==$_REQUEST["course_id"]) { 

echo "Selected"; } ?>><?php echo 

$sql_res1["course_name"]; ?></option>
        <?php
        }
        ?>
       </select>
       </td>
  </tr>
  <tr bgcolor=silver>
    <td>Subjects</td>
    <td>
       <select name="sub_id" id="sub_id">
        <option value="">--Select--</option>
       <?php
       $sql="select * from subjects where 

cat_id='$_REQUEST[course_id]'";
       $sql_row=mysql_query($sql);
       while($sql_res=mysql_fetch_assoc($sql_row))
       {
       ?>
       <option value="<?php echo $sql_res["id"]; 

?>"><?php echo $sql_res["Sub"]; ?></option>
       <?php
       }
       ?>
    </select>
       </td>
  </tr>
</table>
</form>
</body>
</html>

5. Finally go for out put to see the above program. 











That's all for now, kindly subscribe us / comments your response!.

Thank you!




















No comments:

Post a Comment