0

I want to make a "search engine" with people in php. I have two columns. The first is with first_name and the secon is with last name i use this sql syntax:

SELECT * 
FROM users 
WHERE first_name OR last_name LIKE '$search_term%'

I wand the sql to search for first name and for last name the same time with out having one column with first_name and last_name together. Please Help !!!!

John Woo
  • 258,903
  • 69
  • 498
  • 492
alexalikiotis
  • 179
  • 2
  • 2
  • 12
  • (And many other questions, no idea how often this exact code and question came up. Try [our search function](http://www.google.com/search?q=site:stackoverflow.com+php%20search%20database%20first_name%20last_name%20LIKE)!) – mario Feb 24 '13 at 15:16

1 Answers1

0

it should be

SELECT * 
FROM   users 
WHERE  first_name LIKE '$search_term%' AND 
       last_name LIKE '$search_term%'

But the query above performs full table scan because it doesn't use index. For better performance, search about FULL TEXT SEARCH.

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492