0

The result stored in $g is 1 and 2. The following code I've written below, my $array['music'] stores only the last element that is 2. But what I want is to execute my sql query 2 times under foreach and match the value of $g which is 1 and 2 with mu_id (mu_id is the column name from another table music) and store all the rows data of row 1 and 2 in to $array['music'].

It is storing only for the second row (2) not for 1 or it is overwriting it when it is executing for the second time inside loop. If there is any logic to make it work then please let me know.

    foreach($genre as $g)
    {
        echo $g;
        echo "<br>";
        $array['music'] = $m -> where('mu_id', $g ) -> get();
    }
hakre
  • 193,403
  • 52
  • 435
  • 836
Shashi Roy
  • 323
  • 3
  • 7
  • 22
  • What's $g? What's $m? Give your variables appropriate names, so they're easier to follow. We don't need to learn our ABCs again. – Madara's Ghost Apr 30 '12 at 08:36
  • @Truth: The CI Datamapper docs use single letter variables in all their examples, so this is probably just copying those examples. I agree it's a bad habit, but in this case, I would assume `$g` is "genre" and `$m` is "music". I also would just use the full word. – Wesley Murch Apr 30 '12 at 08:38
  • @madmartigan I'm well aware of that. I'm just stating that he shouldn't do it himself, as well as copying examples blindly without understanding the basics of arrays. – Madara's Ghost Apr 30 '12 at 08:40
  • @Truth: Oh ok... I'll take care of that from next time onward... – Shashi Roy Apr 30 '12 at 08:48
  • $g is for genre and $m for music table ( object of music class). – Shashi Roy Apr 30 '12 at 08:50

2 Answers2

6

You're redeclaring the entire array each time rather than adding to it, use this instead:

foreach($genre as $g)
{
    $array['music'][] = $m->where('mu_id', $g)->get();
}

Or even better, less queries:

$array['music'] = $m->where_in('mu_id', $genre)->get();
Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
  • Thanks a lot. As I am new to codeigniter and datamapper , I was wondering how to make it work. This is something like magic to me. I am really happy as this is now working perfectly. What a rapid reply!!! Thanks once again... :) – Shashi Roy Apr 30 '12 at 08:40
  • 1
    Both CI and DM have really good docs, make sure to read them frequently. That said, this was just a fundamental PHP mistake, PHP has really good docs too, make sure to reference them frequently as well. – Wesley Murch Apr 30 '12 at 08:41
0

If you want to store all the data in an array you should be using $array['music'][] instead of $array['music']

Prabhuram
  • 1,268
  • 9
  • 15