search problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sweetcoz
Forum Newbie
Posts: 4
Joined: Tue Jan 09, 2007 4:22 am

search problem

Post 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?
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post 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.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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.
sweetcoz
Forum Newbie
Posts: 4
Joined: Tue Jan 09, 2007 4:22 am

Post by sweetcoz »

if i don't use

Code: Select all

$kwd=$_POST['keyword']
to do my search, what can i use?
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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.
Post Reply