I have the following data in my database:
initial | word
---------------------------
E | Example1
E | Example2
N | Nextexample1
The desired output:
E : Example1, Example2
N : Nextexample1
So for each initial, it should display all the words starting with that initial.
Output at this moment:
E : Example1
E : Example2
N : Nextexample1
My code at this moment:
<?php
$pdo = new PDO('mysql:host=...');
$sql = "SELECT DISTINCT initial, word FROM `exampletable` ORDER by initial ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
if($stmtrecords = $stmt->fetchall(PDO::FETCH_ASSOC))
{
foreach($stmtrecords as $result)
{
?>
<?php echo $result['initial'];?> : <?php echo $result['word'];?>
The question:
I completely understand why I'm getting the wrong output but don't know how to solve it. I guess I need something like a foreach loop within a foreach loop to get the right output, but how to link the words to the correct initial?