How to put category names from the database in the table?

Actually, the point is: there is a database table with columns of user id/categories/products. On the personal page of each user, a table is displayed with a selection from the database of goods entered by him (such as an apple, watermelon, pear, tomato, cottage cheese). I would like them to go not just by enumeration, but separated by category names, for example:
/fruits/
apples
pears
/vegetables/
tomato
etc.
moreover, if the user has nothing in some category, it simply does not need to be inserted into the table (so that there is no empty category without a product). At the moment, the code with the selection is:

<?php 
$result=mysql_query("SELECT id, kats, name FROM characters WHERE account = $myrow2[id] ORDER BY name");
$n=mysql_num_rows($result);
while($table = mysql_fetch_array($result))
{
    echo "<option value='".$table["id"]."' >".$table["kats"].", ".$table["name"]."</option>";
}
?>

What needs to be added to add the necessary categories as subheadings and sort the list by them?


Answer 1, authority 100%

In my opinion GROUP BY katsor ORDER BY kats, name

And in the loop, probably put “if (empty($table['kats'])) continue;

Added:

<?php 
$result=mysql_query("SELECT id, kats, name FROM characters WHERE account = {$myrow2['id']} ORDER BY kats, name");
$Products = array();
while($row = mysql_fetch_object($result)) {
  if (empty($row->kats)) continue;
  if (!isset($Products[$row->kats]))
    $Products[$row->kats] = array();
  $Products[$row->kats][] = array('id'=>$row->id, 'name'=>$row->name);
  }
foreach($Products as $category_name => $items) {
  echo '<option> '.$category_name.'</option>';
  foreach ($items as $item)
    echo '<option value="'.$item['id'].'">-- '.$item['name'].'</option>';
  }
?>

Somehow)