0

I'm trying to convert a mysql_query statement that had the following in it to PDO:

$string = '2, 3, 4, 5, 7, 8';


mysql_query(" ... IN($string) ...");

This works fine with the mysql_query statement, but it will not work with PDO prepare and execute (no results are returned).

What am I missing here?

Nate
  • 26,164
  • 34
  • 130
  • 214

3 Answers3

1

If the query sql works fine with mysql_query, then it will work fine with pdo.

What will not work is if you bind the whole string with just one placeholder. You need to bind for each values for the IN clause.

Example:

$string = '2, 3, 4, 5, 7, 8';
$params = explode(', ', $string);
$sth = $pdo->prepare(' ... IN('.join(',', array_fill(0, count($params), '?')).') ...');
$ret = $sth->execute($params);
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Wow, I can't believe it's that complicated with PDO. That's kind of disappointing.. Thanks for your help. – Nate Jul 10 '12 at 02:01
  • @Nate But if your string is valid value or fixed, you could do `$pdo->query(" ... IN($string) ...");` same as `mysql_query`. – xdazz Jul 10 '12 at 02:08
  • Thanks, I didn't realize I could do that. So, pdo::query is the same as mysql_query? And the string is not a fixed value, but it's taken from a database so I know it's not going to be problematic. – Nate Jul 10 '12 at 21:55
1

Please refer to either PDO binding values for MySQL IN statement or Can I bind an array to an IN() condition?.

I think that is a solution you are looking for since you cannot bind multiple values to a single named parameter in.

Community
  • 1
  • 1
sel
  • 4,982
  • 1
  • 16
  • 22
0

"You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement."

http://php.net/manual/en/pdo.prepare.php

That goes against the whole purpose of prepared statements.

databyss
  • 6,318
  • 1
  • 20
  • 24
  • Wow, this seems like a major problem with PDO. This means I can't use PDO for this query, correct? – Nate Jul 10 '12 at 01:58
  • This is the main advantage of PDO. It prevents things like SQL Injection. It means you want to create an array of all your values and pass that as the input to prepare. – databyss Jul 10 '12 at 02:00