0

I have the following code:

mysql_query("SELECT * FROM list WHERE name LIKE '%'$searchTerm'%' OR description LIKE '%'$searchTerm'%';");

The only problem is, in pure SQL, such a query would look like:

SELECT * FROM list WHERE name LIKE '%asdf%' OR description LIKE '%asdf%'

What I'm confused about is how to put my variables into the string properly, normally a variable in a mysql_query would be surrounded by single quotes, but the addition of the single quotes in the SQL itself is confusing me.

I tried concatenating with . but I don't think that's a good solution.

AKor
  • 8,550
  • 27
  • 82
  • 136

3 Answers3

4
mysql_query("SELECT * FROM list WHERE name LIKE '%$searchTerm%' OR description LIKE '%$searchTerm%';");

Why won't you just...

echo "SELECT * FROM list WHERE name LIKE '%$searchTerm%' OR description LIKE '%$searchTerm%';"

...and see how the query actually will look like..

Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
  • you should always do `mysql_real_escape_string($searchTerm)` on any string passed into a statement otherwise it can be a huge security risk. – Jesse Aug 04 '11 at 20:56
1

I don't know PHP, but I suggest to use a replace function to manage the character "'" into $searchterm. This also allow to avoid sql injections..

Fabio
  • 11
  • 1
0

This is the clearest way to me, using "." to concatenate:

mysql_query("SELECT * FROM list WHERE name LIKE '%".$searchTerm."%' OR description LIKE '%".$searchTerm."%'");

Try and use that, it should work on what you're trying :)

Ozmah
  • 140
  • 8