Php simple search engine?

696

I'm building a search engine that returns data and I'm having trouble displaying a message if there's no results in the database. I'm a beginner at MYSQLI. how would I do something like that? I tired counting the rows and if they're less then 0 to display it but I was having bugs while writing it.

Code:

<?php
$db = mysqli_connect('localhost','root', '', 'searchengine');

if(!$db) {
    die('sorry we are having some problbems');
}


$searchTerm = mysqli_real_escape_string($db,$_GET['term']);

$searchTerm = trim($searchTerm);

if ($searchTerm == '') {
    echo("no key words searched please try again");
}

else
{
$sql = mysqli_query(
    $db,
    sprintf(
        "SELECT * FROM searchengine WHERE name LIKE '%s' LIMIT 0,20",
        '%'. $searchTerm .'%'
    )
);

while($ser = mysqli_fetch_array($sql)) {
    echo "<a href='$ser[pageurl]'>$ser[img]</a>";
}
}

mysqli_close($db);
?>
856

Answer

Solution:

Usemysqli_num_rows...

$sql = mysqli_query(
    $db,
    sprintf(
        "SELECT * FROM searchengine WHERE name LIKE '%s' LIMIT 0,20",
        '%'. $searchTerm .'%'
    )
);
if(mysqli_num_rows($sql) === 0) {
    echo "No results.";
}
746

Answer

Solution:

sincemysqli_fetch_array() returns null when there is no results, you can also put

if ($ser === NULL){
    echo "no results";
}

in the very end

People are also looking for solutions to the problem: Max concurrent connections for php's built in development server

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.