Php search function

I am trying 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 am using. This will only work if you find something that matches the beginning of the result. Is there a way to return values ​​that are of what I am typing as a non-uppercase or lowercase part of the username?

Thankyou

+2


a source to share


4 answers


"%" is a wildcard, so if you also place it in front of your search string (for example %$search%

), it will match $ search anywhere in the username.

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



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

+3


a source


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

Having said this:



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

      

0


a source


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

You can also have a look at MySQL REGEXP function

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

      

0


a source


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

But since you are asking, try comparing everything in uppercase ...

Martin.

-3


a source







All Articles