Reputation: 5063
I've got a database and I'd like to show some results from it without getting duplicates
<?php
$sql = "select * from my_table order by subcategory ASC";
$result = mysql_query($sql) or die($qry);
if (mysql_num_rows($result) == '0') {
echo "No subcategory";
} else {
while ($line = mysql_fetch_array($result)) {
echo $line[subcategory];
echo "<br>";
}
}
?>
It currently shows me all subcategories even if they are duplicated Question: How i can filter the results so that it will only show a subcategory once even if it's in there 4 times.
Do I need to add something to this code to shows only without duplicated?
$sql ="select * from rss order by subcategory ASC";
Upvotes: 1
Views: 320
Reputation: 31
select * from rss order by subcategory ASC
First of all it is a good practive to expand wildcard. List all of the columns instead of using *
There are two approaches on what you're trying to achieve depending on what you need:
Select distinct column1,column2 from rss order by subcategory desc
select max(column1), max(column2), subcategory from rss order by subcategory desc group by subcategory
Upvotes: 3
Reputation: 6937
Use GROUP BY
$sql = "select subcategory from rss group by subcategory"
See the manual for more information: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Upvotes: 3
Reputation: 33865
You can use DISTINCT in your SQL, to avoid getting duplicates back from the database, like this:
select distinct * from my_table order by subcategory ASC
Upvotes: 6
Reputation: 10529
use continue;
keyword and check for duplicates in your while loop
<?php
$sql = "select * from my_table order by subcategory ASC";
$result = mysql_query($sql) or die($qry);
if (mysql_num_rows($result) == '0') {
echo "No subcategory";
} else {
while ($line = mysql_fetch_array($result)) {
if ($dupes[$line['subcategory']])
continue;
$dupes[$line['subcategory']]++;
echo $line['subcategory'];
echo "<br>";
}
}
?>
or just use distinct
$sql ="select distinct * from rss order by subcategory ASC";
Upvotes: 1
Reputation: 174957
You should take a look at array_unique()
. Use it to remove all duplicates from the array.
Upvotes: -1