Page 1 of 1

search problem

Posted: Tue Jan 09, 2007 4:30 am
by sweetcoz
hi all

i use the following code for search:

Code: Select all

$kwd=$_POST['keyword'];
$query = "SELECT * FROM item WHERE item_name LIKE '%".trim($kwd)."%' ";
$result= mysql_query($query, $connect) or die('Query failed: ' . mysql_error());
for example if i look for nokia i have a list of all items with this name
but if i look for nokiia it doesn't return any results
is there something missing in the query?

Posted: Tue Jan 09, 2007 7:44 am
by Begby
LIKE %stuff% means anything that has 'stuff' in the middle of it 'hhjjkhstuffdsds' would match and so would 'stuff house'. However 'stuuff' would not match.

FYIOMG your query is very insecure, never take something from $_POST and just shove it into a query.

Posted: Tue Jan 09, 2007 8:09 am
by JayBird
You may want to look into the SOUNDEX() function for comparing similar words

http://dev.mysql.com/doc/refman/5.0/en/ ... tions.html

Posted: Tue Jan 09, 2007 9:07 am
by CoderGoblin
just a quick note... Soundex doesn't work well with anything other than english.

Using the pspell functionality you could check the spelling after an empty search and find searches from any suggestions from the pspell if no results found.

Posted: Tue Jan 09, 2007 10:25 am
by sweetcoz
if i don't use

Code: Select all

$kwd=$_POST['keyword']
to do my search, what can i use?

Posted: Tue Jan 09, 2007 10:42 am
by CoderGoblin
Using the post value without any validation allows something called SQL Injection attacks to occur. At it's simplest ... what happens if you search for

Code: Select all

'; SELECT 'Hello';
. You may get an error shown which by changing the select statement, people could use to hack your database.

At a minimum. use mysql_real_escape_string

Code: Select all

$kwd=mysql_real_escape_string($_POST['keyword']);
Also if you have no input, why do the SQL and return everything? It makes more sense to display an error and allow the user to search for something.

You should never trust user input, Always validate.