php - Concatenating data in MySQL -
i have following data in database:
initial | word --------------------------- e | example1 e | example2 n | nextexample1 the desired output:
e : example1, example2 n : nextexample1 so each initial, should display words starting initial.
output @ moment:
e : example1 e : example2 n : nextexample1 my code @ moment:
<?php $pdo = new pdo('mysql:host=...'); $sql = "select distinct initial, word `exampletable` order initial asc"; $stmt = $pdo->prepare($sql); $stmt->execute(); if($stmtrecords = $stmt->fetchall(pdo::fetch_assoc)) { foreach($stmtrecords $result) { ?> <?php echo $result['initial'];?> : <?php echo $result['word'];?> the question:
i understand why i'm getting wrong output don't know how solve it. guess need foreach loop within foreach loop right output, how link words correct initial?
you can single sql query.
select `initial`, group_concat(`word` separator ', ') `output` `table` group `initial` order `initial` asc in query asking mysql group records initial , use group_concat() function aggregate each grouping single single row.
using example data
initial | word --------+-------------- e | example1 e | example2 z | zebra n | nextexample o | otherexample o | otherexample2 would return:
initial | output --------+-------------- e | example1, example2 n | nextexample o | otherexample, otherexample2 z | zebra
Comments
Post a Comment