I'm making a searchbar for my page that takes information out of a database. My problem is that if I type in a keyword that IS in the database it shows 3 results, same title, description, and url. For example if I type Borderlands, it will show Borderlands 3 times and will not show Borderlands 2 which is in my database as well.
Here is the code for the functions
- Code: Select all
<?php
function search_results($keywords) {
$returned_results = array();
$where = "";
$keywords = preg_split('/[\s]+/', $keywords);
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword) {
$where .= "`keywords` LIKE '%$keyword%'";
if ($key != ($total_keywords - 1)) {
$where .= " AND ";
}
}
$results = "SELECT `title`, LEFT(`description`, 70) as `description`, `url` FROM `search` WHERE $where";
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;
if ($results_num === 0) {
return false;
} else {
while ($results_row = mysql_fetch_assoc($results)) {
$returned_results = array(
'title' => $results_row['title'],
'description' => $results_row['description'],
'url' => $results_row['url']
);
}
return $returned_results;
}
}
?>
Here is the code for the search results page:
- Code: Select all
<?php
include 'core/init.php';
include 'includes/func.inc.php';
include 'includes/overall/header.php';
?>
<h1>Search Results</h1>
<?php
if (isset($_POST['keywords'])) {
$keywords = mysql_real_escape_string(htmlentities(trim($_POST['keywords'])));
if (empty($keywords)) {
$errors[] = 'Please enter a search term';
} else if (strlen($keywords) < 3) {
$errors[] = 'Your search term must be three or more characters.';
} else if (search_results($keywords) === false) {
$errors[] = 'Your search for '.$keywords.' returned no results';
}
if (empty($errors)) {
$results = search_results($keywords);
$results_num = count($results);
$suffix = ($results_num != 1) ? 's' : '';
echo '<p>Your search for <strong>', $keywords, '</strong> returned <strong>', $results_num ,'</strong> results</p>';
foreach($results as $result) {
echo '<p> <strong>', $results['title'], '</strong> <br>', $results['description'], '...<br> <a href="', $results['url'], '" target="_blank">', $results['url'], '</a></p>';
}
} else {
foreach($errors as $error) {
echo $error;
}
}
}
?>
<?php include 'includes/overall/footer.php';?>
I'm not sure if it's a MySQL error I made or an actual coding error I made...
Thanks in advance for any help I truly appreciate it.

