0

I have a list

$list = array('a','b','c','d','e','f');
$filter_list = join(", " $list);
select * from test where id_col=12 and try_col in ($filter_list);

Anybody could tell me how Can I do this.?

2
  • 1
    What does the "try in $list" part mean? Commented Aug 18, 2011 at 7:51
  • Please provide more information, which database are you using and how interact with it? mysql? mysqli? PDO? Commented Aug 18, 2011 at 7:58

1 Answer 1

3
$list = array('a','b','c','d','e','f');
$filter_list = "'" . join("', '", $list) . "'";
$query = "select * from test where id=12 and try_col in ($filter_list)";
// select * from test where id=12 and try_col in ('a', 'b', 'c', 'd', 'e', 'f')

Note that this will fail if your array values contain '. Here is a workaround:

$list = array("a'a",'a\a','b','c','d','e','f');
$temp = array_map("addslashes", $list);
$query = "SELECT * FROM test WHERE id=12 AND try_col in ('" . implode("','", $temp) . "')";
// SELECT * FROM test WHERE id=12 AND try_col in ('a\'a','a\\a','b','c','d','e','f')
Sign up to request clarification or add additional context in comments.

5 Comments

You should also make sure to escape the values so they can be used properly in an SQL statement
addslashes should be quoted as a string. Also, its much better to use his database-specific escape function. There are several ways to exploit SQL injection when strings are quoted with addslashes and its not locale-aware. Also, the correct way to escape some characters could be different with different RDBMS. That's why I asked him about his database and the API he uses to talk with it.
I am using postgreSQL database.
Using PDO or the pg_ functions?
@shesek: thanks, I thought I was writing jQuery code! Queue, as suggested by shesek I encourage you to use pg_escape_string. I do not have postgres extension so I couldn't test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.