How to Get values in checkbox dynamically, based on dropdown selection in php

I have two fields in database, one is university_name and another one is department_name. I am Displaying university_name in drop down using while loop. When customer selects university_name from dropdown then i want to show its department(department_name) in checkbox. Please help me.

Can you show the script that is not working?

This is my code:

<?php
include('dbconfig.php');
if($_POST['id'])
{
	echo $id=$_POST['id'];
		
	$stmt = $DB_con->prepare("select * from department where university_code=:id");
	$stmt->execute(array(':id' => $id));
	?>
	<?php
	while($row=$stmt->fetch(PDO::FETCH_ASSOC))
	{
		?>
		
		<input type="checkbox" name="department[]" id="department" value="<?php echo $row['department_name'];?>"><?php echo $row['department_name'];?>
        	
        <?php
	}
}
?>

Play about with this and notice the id must have a UNIQUE value.

<?php
declare (strict_types=1);
error_reporting(-1);
ini_set('display_errors', '1');

# include('dbconfig.php');
if(1) //  && $_POST['id'])
{
  # echo $id=$_POST['id'];
    
  # $stmt = $DB_con->prepare("select * from department where university_code=:id");
  # $stmt->execute(array(':id' => $id));
  ?>
  <?php
  # while($row=$stmt->fetch(PDO::FETCH_ASSOC))
  $rows = [
  '1' => 'test-001',
  '2' => 'test-002',
  '3' => 'test-003',
  ];

  fred($rows);

  # while($rows))
  foreach ($rows as $id => $row) {
    # fred($row);
  ?>
    
    <input 
      type  = "checkbox" 
      name  = "department" 
      id    = "department[<?= $id ?>]" 
      value="<?php echo $row; ?>"
     />
     <?php echo $row; ?>
     <br>
          
  <?php
  }
}

function fred($val)
{
  echo '<pre>';
    print_r($val);
  echo '</pre>';
}

If you have a browse back down this section, there are several topics on the subject of populating submenus based on the selection in a first menu. Although you want to use checkboxes rather than a submenu, the principal is the same. IIRC, one of those was about selecting a university and a list of departments for that university.

Presumably your code is called using Ajax when the university is selected. Which part are you having trouble getting to work?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.