1

Column state belongs to table2 and consists of the following varchars: "AL","AK",.. In my php code I have the following String: $states="AL,AK,AZ,IL"; I tried to use it in mySQL query in the following way:

$query = SELECT * FROM 'table2' WHERE  'state' IN('$states');

It does not show any results... What is the correct syntax for those apostrophes?

John Woo
  • 258,903
  • 69
  • 498
  • 492
CHEBURASHKA
  • 1,623
  • 11
  • 53
  • 85
  • Be careful when putting data directly into a query. Make sure that those state abbreviations are coming straight from your code, and that you don't use this technique with data that must be escaped. – Brad May 12 '13 at 02:27
  • As easier alternative (in combination with bound params) you can use `FIND_IN_SET()` instead of the `IN` clause. – mario May 12 '13 at 02:30

3 Answers3

7

The reason why it is not working is because:

  • values in the IN statement is not wrap with single quote
  • column name and table names are wrap with single quotes when it shouldn't be because they are identifiers not string literals

Try this,

$individualStates = explode(",", $states);
$newState = "'" . implode("','", $individualStates) . "'";
$query = "SELECT * FROM table2 WHERE state IN($newState)";

when parsed, the output of the statement is,

SELECT * FROM table2 WHERE state IN('AL','AK','AZ','IL')

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
5

This:

$states_in = "'" . implode("','", $individualStates) . "'";

Is bad. You're opening yourself to SQL injection. Instead, do this:

$states = explode(',', $states);
$states_in = array_map(array($instancePDO, 'quote'), $states);
$states_in = implode(',', $states_in);

If you prefer to use prepared statements instead, this will give you the placeholder string:

$states_placeholder = implode(',', array_fill(0, count($individualStates), '?'));
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • Thank You fro answer. Do you mean XSS? I use only `` Or is there still possibility for injection?‎ – CHEBURASHKA May 12 '13 at 03:15
3
$states = explode(',', $states);
$states = array_map(function($value){return "'$value'";}, $states);
$query = "SELECT * FROM `table2` WHERE  `state` IN(".implode(',', $states).")";

But better to use prepared statement. Read relative question.

Community
  • 1
  • 1
sectus
  • 15,605
  • 5
  • 55
  • 97