(07) 3040 6690

Posts Tagged ‘mysql’

Filtering MySQL Query Results With PHP

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.

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