0

What is the correct query to match string variable with MySQL field? For example:

$var_surname = $_POST['surname'];
$var_surname = strtolower($var_surname);

SELECT surname FROM tblname WHERE LOWER(surname) REGEX $var_surname
..........
..........

if($check > 0)
{
    Surname already exists
} 
else 
{
    Successful
}

Any help will be appreciated.

3
  • 1
    I hope you're sanitizing $var_surname before inserting it into the SQL like that! Commented Feb 23, 2011 at 15:33
  • 2
    In fact, even if you are sanitizing it, running a user-supplied regex on your database server is asking for a DoS attack. It also means you have to sanitize it for SQL while not affecting the regex. Never simply trust what you get from $_POST, it's trivial to view and edit that from client-side. Commented Feb 23, 2011 at 15:40
  • 1
    @Justin I wish I could upvote your comments 100x. Commented Feb 23, 2011 at 15:41

2 Answers 2

1

I don't understand, why are you using REGEX (should be REGEXP by the way) ? Just do

"SELECT surname FROM tblname WHERE LOWER(surname) = '$var_surname'"
Sign up to request clarification or add additional context in comments.

Comments

1

REGEX isn't a valid MySQL operator, it's REGEXP:

SELECT surname FROM tblname WHERE LOWER(surname) REGEXP '$var_surname';

However, REGEXP looks like it's overkill in this case -- the LIKE operator or a simple equality test should work fine:

SELECT surname FROM tblname WHERE LOWER(surname) LIKE '$var_surname';

Or:

SELECT surname FROM tblname WHERE LOWER(surname) = '$var_surname';

And please sanitize $var_surname before using it in your query -- use mysql_real_escape_string or Prepared Statements!

3 Comments

Tried LIKE and = Not validating.Remember I am working with strings.
@Frank How does $var_surname get created?
@Frank: LIKE and = should both work on MySQL string values. Have you tried validating SELECT surname FROM tblname WHERE LOWER(surname) = 'test'; on your database server? The validation failure probably isn't coming from where you think it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.