MrJay
MrJay

Reputation: 13

how to remove duplicate results from mysql query in php?

I'm trying to provide a search function for my PHP site. The users should be able to search rows and columns for their desired query, like "search engine". I tried this php code:

<?php
    $con = @mysqli_connect("localhost", "root", "", "search");
  $output = '';

  if(isset($_POST['search'])) {
    $search = $_POST['search'];
    $search = preg_replace("#[^0-9a-z]i#","", $search);

    $query = mysqli_query($con, "SELECT * FROM sites WHERE (site_title LIKE '%$search%' or site_link LIKE '%$search%' or site_keywords LIKE '%$search%')") or die ("Could not search");
    $count = mysqli_num_rows($query);

    if($count == 0){
      $output = "There was no search results!";
    print $output;

    }else{

      while ($row = mysqli_fetch_array($query)) {

    $site_keywords = $row ['site_keywords'];
    $site_tit = $row ['site_title'];
    $site_link = $row ['site_link'];

    $output .='<div> '.$site_tit.''.$site_keywords.''.$site_link.'</div>';
    print $output;

      }

    }
  }
?>

Everything works just fine but I'm getting duplicate results. I've read a lot of answers and here's I've done so far: I used SELECT DISTINCT * FROM .... and also SELECT DISTINCT site_id FROM .... but didn't return any result. I tries GROUP BY but they didn't remove the duplicates and returned nothing. I also applied PHP array_unique() on $row = mysqli_fetch_array($query) in where condition, but it also didn't return any result. If I can do this by using only SQL please or I have to remove duplicates by PHP like using a function, please guide me. Thanks in advance.

Upvotes: 1

Views: 1323

Answers (1)

Move:

print $output;

outside the loop.

Right now $output is being printed every time through the loop. If your results are A,B,C then your output will be A,A,B,A,B,C (with divs, etc.)

Upvotes: 4

Related Questions