1

I have a form where a user can type in the firstname to search, my query is not returning the correct results, what am I doing wrong?

$sfn = $_POST["Text1"];
$sql = "SELECT * FROM ex_usrs WHERE firstname LIKE '$sfn'";
...
2
  • 2
    You really should escape the stuff you put in a query... Security, anyone? Commented Dec 27, 2011 at 14:24
  • I will start with that, thank you, it's for an internal site, but still, it has to be done Commented Dec 27, 2011 at 14:25

4 Answers 4

5

Maybe you should add %-signs to your keyword like this:

$sql = "SELECT * FROM ex_usrs WHERE firstname LIKE '%$sfn%'";
Sign up to request clarification or add additional context in comments.

Comments

3

Your query will only return rows where firstname is equal to $_POST["Text1"]. When you use LIKE you can use a wildcard (%) to represent any number of characters.

  • This will find rows where firstname starts with $_POST["Text1"].

    SELECT * FROM ex_usrs WHERE firstname LIKE '$sfn%'
    
  • This will find rows where firstname ends with $_POST["Text1"].

    SELECT * FROM ex_usrs WHERE firstname LIKE '%$sfn'
    
  • This will find rows where firstname contains $_POST["Text1"].

    SELECT * FROM ex_usrs WHERE firstname LIKE '%$sfn%'
    

Note: Never use variables from $_POST without escaping them first. What if I searched for "O'Neil" (or worse "'; DROP TABLE ex_users; -- ")?

Comments

3

You should use %searchterm% - include the % wildcards.

$sql = "SELECT * FROM ex_usrs WHERE firstname LIKE '%$sfn%'";

Comments

1

It should be

 "SELECT * FROM ex_usrs WHERE firstname LIKE '%$sfn%'"

Comments

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.