0

When I run the query below I keep getting the values twice. The array holds [1,2,1,2] and it should hold only values [1,2]. Could someone explain to me why I get the duplicate values?

$grusnro = 0;

while (!empty($grus[$grusnro ]))
{
  $catid="SELECT cat_id FROM  catgroup WHERE group_id='$grus[$grusnro]'";
  $catidsult=mysql_query($catid);

  while($grunamerow = mysql_fetch_array($catidsult, MYSQL_ASSOC))
  { 
    $catgroup[]=$grunamerow['cat_id'];  
  }

  $grusnro = $grusnro +1;
}

When I run from command-line I get the result [1,2]. I have checked that the group_id values are only once in the $grus array. So why the duplicates?

2
  • can you try print_r($grus) at the begining of this code to see what is the content of that array? And I would also print $grusnro at end of the first while loop to see if the value is incrementing up till 3. Commented May 19, 2011 at 9:25
  • To remove dupplicate values of an array, you may also use array_unique. Now, if Emil solution works as you pointed out, can you accept his solution? Commented May 19, 2011 at 9:58

1 Answer 1

2

I propose this simplified version of your code, which will perform much better:

$catgroup = array(); //Making sure $catgroup is an empty array
if(!empty($grus)) {
  //Fetch all groups in the same query
  $grusids = implode("','", $grus);
  $catid = 'SELECT DISTINCT cat_id FROM catgroup WHERE group_id IN(\''.$grusids.'\')';
  $catidsult = mysql_query($catid);
  while($grunamerow = mysql_fetch_array($catidsult, MYSQL_ASSOC))
  {   
    $catgroup[] = $grunamerow['cat_id'];
  }
}

Notice the use of the DISTINCT keyword in SQL to only fetch unique cat_ids.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.