MySQL (or PHP?) group results by field data

This would my solution, althoug is not elegant at all

<?php
$dbc = new MySQLI(DBHOST,DBUSER,DBPASS,DB);
$result = $dbc->query("
SELECT
p.Group as 'group',
GROUP_CONCAT(name) as names
FROM prueba p
GROUP BY p.Group
");
?>
<table>
<tr>
    <th>Group</th>
    <th>Name</th>
</tr>
<?php while($row = $result->fetch_assoc()){
    $names = split(",",$row["names"]);
?>
    <tr>
        <td><?php echo $row["group"] ?> </td>
        <td><?php echo $names[0]; array_shift($names) ?></td>
    </tr>
    <?php foreach( $names as $name){ ?>
        <tr>
            <td></td>
            <td><?php echo $name ?></td>
        </tr>
    <?php } ?>
<?php } ?>
</table>

Leave a Comment