Question

I'm trying to create a search engine for my website where users can enter keywords and the PHP script will search the 'name' and 'description' columns of my fyp_items table. So far I have managed to break down the input to an array of words and am try to execute a SELECT query on my database.

THE ISSUE is that it fails to find the items even if the keyword matches that of the data in the table. Below is my script...I hope someone can help me.

if(empty($_POST)=== false){
    $output = '';
    $error = '';
    $input = $_POST['search_input'];
    $i=0;
    if($input){
        $keyword = explode(" ", $input);
        require ('core/dbconnection.php');
        //If a user is logged in check if the user is Admin or Customer. 
        if(isset($_SESSION['userid'])){ 
            if($admin == 1){
            }
        }else{
            //If user is not logged in search items table only.
            $search_items = "SELECT * FROM fyp_items WHERE ";
            foreach($keyword as $k){
                $k = mysql_real_escape_string($k);
                $i++;
                if($i == 1){
                    $search_items .= "name LIKE '$k' OR description LIKE '$k'";
                }else
                    $search_items .= " OR name LIKE '$k' OR description LIKE '$k'";
            }
            $item_qry = mysql_query("$search_items")or die(mysql_error());
            $numrows = mysql_num_rows($item_qry);
            if($numrows > 0){
                $output = 'found it';
            }else
                $error = '<p class="pageerror">Sorry, what you were looking for was not found.</p>';
        }
    }else
        $error = '<p class="pageerror">Please enter your search terms.</p>';

I have tested the post by echoing the output and I have also echoed the $search_items variable to get this... http://awesomescreenshot.com/05c2fwytac

Your help will be much appreciated!

Was it helpful?

Solution

You're building an incorrect query string, that'll be something like

SELECT ... WHERE name LIKE 'foo' OR description LIKE 'foo'

a LIKE comparison without wilcards is pointless. You've functionally got the equivalent of

SELECT ... WHERE name='foo' OR description='foo'

The wildcards allow substring matching in the fields:

SELECT ... WHERE name='%foo%' OR description = '%foo%'

so the word foo can appear ANYWHERE in the field and match. Right now your query will only match if foo is the ONLY thing in either field.

And these sorts of queries are highly inefficient, especially as the number of search terms climbs. You should be suing a fulltext search: https://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top