I’ve made a simple search engine for my website and despite my efforts to get it to work all I ever get is the error message i created should there be no results.
Here is the search engine code:
error_reporting(-1);
ini_set('display_errors', true);
$var = $_GET['q'];
$trimmed = trim($var);
if ($trimmed == '')
{
$error = 'Please enter a search term.......';
include 'error.html.php';
exit();
}
if (!isset($var))
{
$error = 'A search term is required to perform a search.......';
include 'error.html.php';
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$sql = "SELECT * FROM story WHERE storytext LIKE \\"%$trimmed%\\" ORDER BY RAND LIMIT(10)";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Sorry your search returned no results.';
include 'error.html.php';
exit();
}
while ($row = mysqli_query($result))
{
$stories[] = array('id' => $row['id'], 'title' => $row['storytitle'], 'text' => $row['storytext']);
}
Use single quotes around strings in the query, use mysqli_real_escape_string to sanitize user input before using it in a query, and for debugging purposes use the ‘or die’ construction to get more detailed info in case of an error:
$sql = "
SELECT *
FROM story
WHERE storytext LIKE '%" . mysqli_real_escape_string($trimmed) . "%'
ORDER BY RAND
LIMIT(10)
";
$result = mysqli_query($link, $sql) or die("mysqli error " . mysqli_error() . " in query $sql");
first, you ~removed~ the parts of the query which had the syntax error – congratulations
second, the reason you got an empty set back is because there are currently no rows in your story table which have a storytext column consisting entirely of the single word ‘this’
well, for one thing, you cannot use an equivalent to the dreaded, evil “select star” in your WHERE clause
you will have to write a separate condition for every column that you want searched
note that if you’re searching for words, for example, it wouldn’t make sense to include the story id or published date among the colulmns being searched