I'm working on a simple search engine for my website, I managed to make one with php and a MySQL database and it works but it will only show results if I first put a space and then the input, directly giving the input results in my own made message that their where no search results.
Example, above is how it works now and below is an example that it doesnt without a space work :
Image link where it becomes clear: https://i.stack.imgur.com/mD0rO.png
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<center>
<form action='search.php' method='get'>
<input type='text' name='k' placeholder='Search' size='50' />
<input type='submit' value='Search'>
</form>
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM search_engine WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each$' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connect
mysql_connect ("***", "***", "***") or die("Could not connect to database!");
mysql_select_db ("***") or die("Could not find database!");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<br><br> Results: $title <br> Description: $description <br> Link: $link ";
}
}
else
echo "<br><br>No results found for $k";
//
?>
</center>
</body>
</html>
Does someone have an idea why it only works with the space before the input? Also I heard form some people that the codes are not save, can someone tell me if it is possible to make it saver without many changes to my code.
Thanks in advance!