0

How can I search a keyword in multiple columns in mysql syntax?

Now I have a variable $phone, that store the form input, and use the syntax to search in a single column:

SELECT * FROM db.table WHERE 'phone1' = '".$phone."';

How I make that search through columns 'phone1', 'phone2', 'phone3' and 'phone4'?

Thanks

1
  • 1
    I trust that you have sanitized $phone accordingly, too? Commented Jan 22, 2013 at 18:16

2 Answers 2

5

Use OR in your WHERE clause

SELECT * 
FROM db.table 
WHERE 'phone1' = '".$phone."'
OR 'phone2' = '".$phone."'
OR 'phone3' = '".$phone."'
OR 'phone4' = '".$phone."'
Sign up to request clarification or add additional context in comments.

8 Comments

But @WilliamdeCastro beware if $phone contains the string "' OR 1=1 --"
Yes, they don't show enough code to say whether or not they were sanitizing and/or escaping their data so I didn't elaborate on it.
@lc $pohne will ever have a simple numeric string
@WilliamdeCastro How do you guarantee that?
I'm sorry, you simply cannot rely on JS alone to sanitize your DB strings. And, as for running on intranet, never underestimate your users...
|
1

Why not try in: =)

SELECT * 
FROM db.table 
WHERE '".$phone."' in (`phone1`, `phone3`, `phone3`, `phone4`)
;

9 Comments

Not sure how logical it is in terms of performance.. tested table:(sqlfiddle.com/#!2/615bf/1) Please leave a comment for the downvotes as or is same as in and explain plan shows the same
It is, but you should use backflicks instead of single quotes for field names, and you have a mismatch in your quotes anyway.
Your answer is incorrect and will not work in its current form, hence the downvote.
That's all you needed to do. There was no need to get childish about it now, was there? ;-)
Why not then downvote the above answer for the same? if you are downvoting it has to be consistent on your reasoning for all. Isn't it?
|

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.