I'm trying to implement a search bar into my website, which searches the 'product' table in my database.
The results page of this search shows many of the same results,
for example,
My table product has 16 rows of data, but the search results page shows 4 times that.
My product table also has a column called 'productHasCategory', as this relates to the category table.
From google searches, I think the problem is something to do with my categories, but I can't find a solution from just Google search alone.
Here's my code:
Code: Select all
<?php
require_once('inc/global.inc.php');
# search.inc.php
/*
* This is the search content module.
* This page is included by index.php.
* This page expects to receive $_GET['terms'].
*/
// Redirect if this page was accessed directly:
if (!defined('BASE_URL')) {
// Need the BASE_URL, defined in the config file:
require_once ('../includes/config.inc.php');
// Redirect to the index page:
$url = BASE_URL . 'index.php?p=search';
// Pass along search terms?
if (isset($_GET['terms'])) {
$url .= '&terms=' . urlencode($_GET['terms']);
}
header ("Location: $url");
exit;
} // End of defined() IF.
// Print a caption:
echo '<h2>Search Results</h2>';
// Display the search results if the form
// has been submitted.
if (isset($_GET['terms']) && ($_GET['terms'] != 'Search...') ) {
$terms = $_GET['terms'];
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die *('Error connecting to MySQL server');
// Query the database.
$query = "SELECT DISTINCT product_id, title, price, img FROM product WHERE title LIKE '%$terms% '";
$result = mysqli_query($dbc, $query);
// Fetch the results.
$row = mysqli_fetch_array($result);
// Print the results:
while ($row = mysqli_fetch_array($result)) {
$output[] = '<ul>';
$output[] = '<li>'.$row['title'] .': £'.$row['price'].'<br /><img src="'.$row['img'].'" alt="'.$row['title'].'" /></li>';
$output[] = '</ul>';
echo join('',$output);
}
}
else { // Tell them to use the search form.
echo '<p class="error">Please use the search form at the top of the window to search this site.</p>';
}
?>
Thanks for reading,
Andrew.