简体   繁体   中英

Returning rows from database based on search query

I am having a product table with following schema:

products (itemname VARCHAR(50), itemid INT(10));

Sample records are shown below ( itemname , itemid ):

  • blackberry curve 3g (black), 1
  • samsung ace, 3
  • blackberry curve 3g (white), 2
  • apple iphone 4 32gb (black), 4

Now suppose user enters the query into the search box of the website and accordingly results are displayed. ie if user enters blackberry then Blackberry mobiles should be displayed

I am looking answers for the following questions:

  1. How can search text be matched with the items? For example: user may enter blackberry in the search box then how it can be searched? Should I search for blackberry word as a sub-string of itemname column of the above table?
  2. If the user enters two words like: apple 32gb . Now if I use the above mentioned method of sub-string then it wont work because there is no row in the table having apple 32gb as sub-string. How to search in this case?
  3. If the user enters a very generic search text like: mobiles . In this case, all the mobile phones should be displayed. Matching the itemname as a sub-string will not work in this case also.
  4. User may enter search text: apple 32gb black color . In this case, apple products of 32GB capacity and black color should be displayed.

I know that implementing the search 100% correct is not possible. I am just looking for hints/how to proceed. I am using PHP, MySQL, Apache.

What kind of database is this, if MySQL you can enabled fulltext search on the field and then just a simple query will get you the results you expect.

for many word searching I would do something like this:

$searchArray = explode(" ", $searchString);
foreach ($searchArray as $word)
{
    //add an OR clause to your sql query like the following
    $query .= "OR itemname like %".$word."%";
}

the other questions are far more complicated, but I hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM