-2

I'm trying to create a catalog where you can search in based on arguments you give. naam is the name of the product and woord are the given characters. later on in the script i glue this part of the query to the first part.

Thank you

if(strlen($whereQuery) > 0) 
    $whereQuery .= 'AND naam LIKE '%'.$woord.'%'';
else
    $whereQuery = 'WHERE naam LIKE '%'.$woord.'%'';
John Woo
  • 258,903
  • 69
  • 498
  • 492

4 Answers4

1

I'd rather use double quote to avoid confusion,

if(strlen($whereQuery) > 0) 
    $whereQuery .= " AND naam LIKE '%" .$woord. "%' ";
else
    $whereQuery = " WHERE naam LIKE '%" .$woord. "%' ";

or simply,

if(strlen($whereQuery) > 0) 
    $whereQuery .= " AND naam LIKE '%$woord%' ";
else
    $whereQuery = " WHERE naam LIKE '%$woord%' ";

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
  • 1
    or just: `$whereQuery = " WHERE naam LIKE '%$woord%' ";` since you are in double quotes anyway... – Naftali Feb 20 '13 at 15:44
1

Use double quotes.

Or escape the single quotes.


Also please do not do what you are currently doing.

Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

You need to escape the quotes that are part of the query:

if(strlen($whereQuery) > 0) 
    $whereQuery .= 'AND naam LIKE \'%'.$woord.'%\'';
else
    $whereQuery = 'WHERE naam LIKE \'%'.$woord.'%\'';

Or use a mix of single and double quotes.

jeroen
  • 91,079
  • 21
  • 114
  • 132
0

Any editor with colour-coding would immediately show you the problem. Just look at your code in the question.

Try this:

$whereQuery = ($whereQuery ? $whereQuery." AND" : " WHERE")." naam LIKE '%".$woord."%'";

This avoids repeating the whole "LIKE" part twice ;)

Also, make sure you have properly escaped $woord. mysql_real_escape_string is NOT enough in this case. You also need to run it through preg_replace("/[%_]/","\\$1",$woord); to escape special characters in a WHERE clause.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592