Search code examples
phphtmldropdown

PHP dropdown menu values sorting and separation with respect to similar ID's


Here is the mysql table named "subject"

| ID | Name |
|----|------|
| 32 | Name1 |
| 32 | Name2 |
| 32 | Name3 |
| 28 | Name4 |
| 28 | Name5 |
| 33 | Name6 |
| 33 | Name7 |
| 41 | Name8 |
| 55 | Name9 |

I would like to give a separation after all the similar ID's

<select>
<?php

   $count_line = 0;
   $sql="SELECT * FROM subject";
   $result=mysqli_query($conn, $sql);
   while($row = $result->fetch_assoc()) {

?>     
 <option><?php echo $row['Name'];?></option>
<?php 
     if ($count_line == 2) {
       echo "<optgroup label='--------------------'></optgroup> ";
       $count_line=0;
     }
     $count_line++;
}   
?>
</select>

In my code separate line will show after every two records.I would like to display the separate line after every similar ID's in the dropdown menu.

I would like to get the output like as shown in the picture. enter image description here

Please do help someone to solve it.


Solution

  • You can try,

    <select>
    <?php
    $count_line = 0;
    $row_id = '';
     $sql="SELECT * FROM subject";
    $result=mysqli_query($conn, $sql);
    while($row = $result->fetch_assoc()) {
    ?>     
     <?php 
    if($count_line != 0 && $row_id != $row['ID']) 
    {
    echo "<optgroup label='--------------------'></optgroup> ";
    }
     <option><?php echo $row['Name'];?></option>
    $count_line++;
    $row_id = $row['ID'];
    }   
    ?>
    </select>