Thursday, 3 May 2012

Make a case sensitive MySQL Search

You might have noticed that when you search for a string in MySQL using '=' or 'LIKE' keyword, the search is not case sensitive. That is you will receive all records irrespective of the case (Uppercase or Lowercase). This is advantageous in several cases, but there are situations when you want the search to be case sensitive.


Suppose you are using the search query to validate a user login. In this case it is not desirable to make the password case insensitive. If you run a normal query as given below, you will get the record even though the password is not proper.

SELECT * FROM login WHERE `name` LIKE '$name' AND `password` LIKE '$password';

Suppose if the actual password is 'myPasSworD' the above query will return the record even if password entered is 'mypassword' or 'MYPASSWORD' or even 'MyPaSsWoRd'.

To avoid this, you can use the keyword BINARY along with the LIKE keyword as shown below.

SELECT * FROM login WHERE `name` LIKE '$name' AND `password` LIKE BINARY '$password';

The use of BINARY keyword will cause the search to be case sensitive. In this case, the password will be accepted only if it is given as 'myPasSworD'.

No comments:

Post a Comment