0

i have such a table:

r_id     date       recipe_name

 1   2012-05-20  Cheese Bread
 1   2012-05-21  Cheese pie
 2   2012-05-20  Spanish Bread

I would like to get all the data under r_id 1 to be in a single row how can i do that using Sql.I need to achieve something like this:

 r_id      recipe_name

 1    Cheese Bread,Cheese pie
 2    Spanish Bread

how can i do this using php too?

2 Answers2

1

Use GROUP_CONCAT

SELECT r_id, GROUP_CONCAT(recipe_name)
FROM yourTable
GROUP BY r_id
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • thanks it worked well,but now How can I display the recipe_names separately as links using php.+2 for chinese speed – user3253289 Jul 21 '14 at 08:58
  • For PHP version you can see the answer by FuzzyTree, no need to re-invent the wheel by writing another answer on top of that. – Hanky Panky Jul 21 '14 at 09:02
  • Fuzzy uses fetch assoc().Iam trying to use $rows=$result->fetch_object( ),how can i access the recipe names this time – user3253289 Jul 21 '14 at 09:28
0

Here's the php version

$query = "SELECT id, recipe_name FROM myTable";
$rs = mysqli_query($query);
$results = array();

while($r = mysqli_fetch_assoc($rs)) {
    $results[$r['id']][] = $r['recipe_name'];
    //$results[$r['id']][] = "<a href=''>".$r['recipe_name']."</a>";
}

foreach($results as $id => $recipes) {
    print $id . ' ' . implode(',', $recipes) . "<br>";
}
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85