I do not post the final solution. But I hope it would give you an idea...
The table `names` should contain the field `category_id` - id of the category to which it belongs.
You simply names like this:
Here I assumed that category_id is always set to some category id and could not be null.
FROM names AS n
JOIN categories AS c
Then you pass the resultset in a loop and show the names for each category.
You could even do most of the work right in the SQL by using GROUP_CONCAT() ... (provided the DB is MySQL I mean)