I'm trying to create a simple search page for my website, but don't know how to search my database without using something like strpos()
, which returns all results containg the query in order they are listed in the database.
I have tried to use strpos()
, but I only get a list of results containing the query. Yes, I know that that is exactly what it does, but what would the better solution be?
Right now, my PHP looks like the below
$dbc = mysqli_connect ('localhost', 'username', 'password', 'DBName')
or die ('Error connecting to the database.');
//Get and cleanse the query
$q = mysqli_real_escape_string($dbc, strtolower($_GET['q']));
$query = "SELECT * FROM games";
$result = mysqli_query($dbc, $query)
or die('Error querying the database');
while($row = mysqli_fetch_array($result)) {
$name = strtolower($row['name']);
$img = $row['img'];
$description = $row['description'];
$url = $row['URL'];
$creator = $row['creator'];
if (strpos($name, $q) !== false){
$name = $row['name'];
echo "
<div class='result'>
<a class='result-link' href='$url'>
<p class='name'>$name</p>
</a>
<p class='url'>$url</p>
<p class='description'>$description</p>
</div>
\n";
}
}
mysqli_close($dbc);
Please note that I am using strtolower()
as a way to make the query and result non-case sensitive.
I expect the results would be in the order that they show up in the database, which makes sense and is happening, but what can I do to sort them?