tags:

views:

72

answers:

4

I am attempting to create a search function for user profiles on my site.

$search= $_POST['search'];
$res=mysql_query("SELECT * FROM ".TBL_USERS." WHERE username LIKE '$search%'");

This is the code I use. This will only work if you search something that matches the start of the result. Is there any way I can return values that have what i type as part of the username regardingless of upper or lower cases?

Thankyou

A: 

You should really add some sort of data cleansing, you should never take raw post/get data and insert it directly into a query.

With that said:

$search= strtolower($_POST['search']);
$res=mysql_query("SELECT * FROM ".TBL_USERS." WHERE LOWER(username) LIKE '$search%'");
Harold1983-
A: 

As you are using LIKE you can use the % wildcard on both sides of the input, this will return any users where $search is part of the username.

You may also want to look at MySQLs REGEXP function

$search= mysql_real_escape_string($_POST['search']);
$res=mysql_query("SELECT * FROM ".TBL_USERS." WHERE username LIKE '%" . $search . "%'");
Neil Aitken
+3  A: 

"%" is the wildcard, so if you also place it in front of your search string (like %$search%) it will match $search anywhere in username.

Use "LOWER" in SQL to make your username lowercase and "strtolower" in PHP to do the same, then execute the query to get case-insensitive results.

And as David Dorward said: read bobby-tables.com before you do anything else!!!

Select0r
Thankyou, I understand SQL injection, thats an old piece of code. I shouldn't have put it up! Thanks for the answer.
Luke
A: 

You need to read about the terms "SQL Injection" and "PHP Prepared Statements" - Google for them... This is FAR more important that the question you have asked.

But since you ask, try the comparison all in upper case...

Martin.

Martin Milan
Thankyou for the response, I know about SQ
Luke
SQL injection, just added old code before I knew!
Luke
I love StackOverflow - I answer the question, I point our a far more important point, and I get downvoted for it. I don't suppose whoever downvoted me would care to explain? I genuinely don't see what I have done wrong here...
Martin Milan