2

I've built a simple search bar for my website, and if my query looks like this, it works great:

$sql = query("SELECT id, firstname, lastname, username, location FROM 
users WHERE firstname LIKE '%" . $search_query . "%' LIMIT 20");

but if i write it like that, it echoes a SQL Syntax error :

$sql = query("SELECT id, firstname, lastname, username, location FROM 
users WHERE firstname, lastname, username, location  LIKE '%" . $search_query . "%'   
LIMIT 20");

The difference between the 2 queries is that the 2nd one will search through multiple columns which is what i need since my users can search either for a name or a city.

How should I re-write it ?

Prix
  • 19,417
  • 15
  • 73
  • 132
Caro_deb
  • 279
  • 1
  • 8
  • 25

3 Answers3

1

You have to repeat the LIKE statement for each field, unfortunately.

SELECT id, firstname, lastname, username, location FROM users 
WHERE firstname LIKE '%" . $search_query . "%'
OR lastname LIKE '%" . $search_query . "%' 
OR username LIKE '%" . $search_query . "%'
OR location LIKE '%" . $search_query . "%'
LIMIT 20
apartridge
  • 1,790
  • 11
  • 18
1

The keyword LIKE does not work like that. Try this:

$like_string = "'%$search_query%'";

$query = "SELECT id, firstname, lastname, username, location
FROM users
WHERE firstname LIKE $like_string OR
lastname LIKE $like_string OR
username LIKE $like_string OR
location LIKE $like_string
LIMIT 20";

$sql = query($query);

As others will tell you, it is smart to account for SQL injection and perform sanity and validity checks before accepting any user data. Take a look at this question on how to prevent SQL injection.

The PDO extension or the mysqli extension is preferred for MySQL and mysql_ functions have been deprecated (as can be seen throughout the documentation).

Community
  • 1
  • 1
BLaZuRE
  • 2,356
  • 2
  • 26
  • 43
0

You need to specify each column's search condition separately:

$sql = query("SELECT id, firstname, lastname, username, location
FROM users
WHERE firstname LIKE '%$search_query%'
OR lastname LIKE '%$search_query%'
OR username LIKE '%$search_query%'
OR location LIKE '%$search_query%'
LIMIT 20");

As you can see, I've removed the concatenation - since you're using double quotes, variables can go directly into the query.

Also, I hope $search_query has been santised, or you're opening yourself upto SQL injection attacks; really, you should be using parameterised queries by now.

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134