Reham Fahmy
Reham Fahmy

Reputation: 5063

Remove Duplicated from results

I've got a database and I'd like to show some results from it without getting duplicates

Example

<?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

Answers (6)

user1058433
user1058433

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:

  1. Select distinct column1,column2 from rss order by subcategory desc
  2. select max(column1), max(column2), subcategory from rss order by subcategory desc group by subcategory

Upvotes: 3

djdy
djdy

Reputation: 6919

Look into SELECT DISTINCT and GROUP BY

Upvotes: 3

Eljakim
Eljakim

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

Christofer Eliasson
Christofer Eliasson

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

Martin.
Martin.

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

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

You should take a look at array_unique(). Use it to remove all duplicates from the array.

Upvotes: -1

Related Questions