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.
SELECT DISTINCT site_id FROM...and you get NOTHING? I don't believe it. At any rate, @manassehkatz has definitely found an issue in your PHP that may be more of a culprit than your sql.mysqliis significantly less verbose, making code easier to read and audit, and is not easily confused with the obsoletemysql_queryinterface. Before you get too invested in the procedural style it’s worth switching over. Example:$db = new mysqli(…)and$db->prepare("…")The procedural interface is an artifact from the PHP 4 era whenmysqliAPI was introduced and should not be used in new code.mysqliyou should be using parameterized queries andbind_paramto add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put$_POST,$_GETor any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake.