Filtering MySQL Query Results With PHP

By: , On Tuesday, January 27th, 2009

For a while I’d been trying to figure out how to output a mysql query while excluding rows with duplicate values for a specific pair of column values, and then ordering by the most recent timestamp. Some if the phrases I ended up searching the web for were get all from distinct, order by then group by, exclude / remove duplicates, find duplicates, count duplicates and so on.

My ultimate solution was pretty simple and I hope it will help any one else looking for a solution to a similar problem.

$query="SELECT * FROM TABLE01 ORDER BY timestamp DESC";
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){          
$valuePair=$row['col01'].$row['col02'];
$combinations[]="";
if(!(in_array($valuePair,$combinations))){
Arbitrary Code to Execute
}
$combinations[]=$valuePair;
}//end while loop

In the above code I created a variable referred to as valuePair containing the pair of values I want to check for duplicates, and an empty array called combinations which I then use to contain the valuePair’s, and check for duplicates with my if statement, if the valuePair is not found in my combination array then the code is executed, if the valuePair is contained in the combination array then the code is not executed, at the end of each while loop iteration, the new valuePair is added to the combination array.

Related posts:

  1. Add Images to Your WordPress Summary Feed
  2. Filtering Your Social Feeds
  3. Get Your Latest Tweet with PHP
  4. Redirect a WordPress Post to its Permalink
  5. DHTML / JavaScript Marquee

2 Responses to “Filtering MySQL Query Results With PHP”

  1. Andy Bailey Says:

    I sometimes spend an unhealthy amount of time figuring out a long convoluted sql statement, your solution seems to be quite elegant!

    Andy Bailey’s last blog post..Chinese new year with infinity hoovers. video blog post

    Wardell Reply:

    @Andy Bailey, Thank you, and thanks for stopping by. :D

© Wardell Design 2012
Entries (RSS) and Comments (RSS).