I have a table called "department_categories" that has 3 columns "id", "category" and "department":
id | category    | department
1  | chainsaw    | garden and home
2  | jet-ski     | lifestyle
3  | generator   | garden and home
4  | tractor     | agriculture
5  | rtv         | lifestyle
Now what I want to achieve is to display all categories within each department. The following query
$sql = "SELECT category, department FROM department_categories GROUP BY department
results in the following:
garden and home | lifestyle | agriculture
                |           |
chainsaw        | jet-ski   | tractor
Which makes sense as GROUP BY groups all rows based the specified column. However the result I'm looking for is:
garden and home | lifestyle | agriculture
                |           |
chainsaw        | jet-ski   | tractor
generator       | rtv
I came across the following stackoverflow question. Which seems like a similar issue I'm having but I can't wrap my head around it.
Here is the full script I'm working with for more clarity:
<?php
$host       = "localhost";
$username   = "root";
$password   = "";
$dbname     = "auro-rudamans";
$dsn        = "mysql:host=$host;dbname=$dbname";
$options    = array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
              );
$connection = new PDO($dsn, $username, $password, $options)
try {
    $sql = "SELECT category, department FROM department_categories GROUP BY department";
        $statement = $connection->prepare($sql);
        $statement->execute();
        $result = $statement->fetchAll();
    }
    catch(PDOException $error) {
      echo $sql . "<br>" . $error->getMessage();
    };      
?>
<?php foreach ($result as $row) : ?>
<ul>
    <h1><?php echo $row['department']; ?></h1>
    <li><?php echo $row['category']; ?></li>
</ul>
<?php endforeach; ?>
Any assistance would greatly be appreciated. Thanks
 
     
    