1

How can I write the following request using PDO?

$query = "SELECT test FROM table WHERE cond IN(1,2,3)";

I tried this, but it is not working:

$query = "SELECT test FROM table WHERE cond IN(?)";
$params = array($condArray); 
$result = sqlsrv_query($connConfig, $query, $params) ;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sdespont
  • 13,915
  • 9
  • 56
  • 97
  • 2
    I don't think PDO supports table-valued parameters (and if it did, your syntax would be a tad off) – Damien_The_Unbeliever Apr 18 '13 at 07:03
  • No, it doesn't work this way: `?` should be a scalar value, not an array. One possible approach is to create a string of `?,?,...` according to array's length. – raina77ow Apr 18 '13 at 07:03
  • @raina77ow ok but I don't know how many entries my array have. I would avoid to create dynamically the number of `?` expected if possible – sdespont Apr 18 '13 at 07:05
  • @Damien_The_Unbeliever are you saying that the only possibility is to create dynamically the right number of parameters `?` and pass the array values separately in `$params`? – sdespont Apr 18 '13 at 07:08
  • 1
    http://stackoverflow.com/questions/15990857/reference-frequently-asked-questions-about-pdo#15991146 – Your Common Sense Apr 18 '13 at 07:12
  • 1
    If you pass SQL Server a single, scalar, parameter, then that is how it will treat it. Just because a *single* string *contains* commas, doesn't mean that SQL server should treat it as *multiple* strings/arguments. There are some ways to fudge things, by passing such a string and implementing a `split` function on the server (searches for SQL Server split should yield good results), or by passing XML and using the servers XML processing abilities to shred it. – Damien_The_Unbeliever Apr 18 '13 at 07:14
  • @YourCommonSense thanks, your link was helpful – sdespont Apr 18 '13 at 07:21

1 Answers1

0

@Your Common Sense comment do the trick.

Reference - frequently asked questions about PDO

$ids = array(1,2,3);
$in  = str_repeat('?,', count($arr) - 1) . '?';
$sql = "SELECT * FROM table WHERE column IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($ids);
$data = $stm->fetchAll();
Community
  • 1
  • 1
sdespont
  • 13,915
  • 9
  • 56
  • 97