Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding parameters for WHERE IN clause with PDO

Tags:

php

mysql

pdo

My code:

$myArray = implode($myArray, ',');
$sth = $dbh->prepare('SELECT foo FROM bar WHERE ids IN (:ids)');
$sth->bindParam(':ids', $myArray);
$sth->execute();
$result = $sth->fetch();
echo $sth->rowCount();

Always shows a count of 1, but when I skip the parametrization and just add the variable itself in it's place, I get an accurate count. What's going on here?

like image 332
Radu Avatar asked Aug 12 '11 17:08

Radu


People also ask

What is PDO parameter binding?

The PDOStatement::bindParam() function is an inbuilt function in PHP that is used to bind a parameter to the specified variable name.

What is the difference between bindParam and bindValue?

bindParam is a PHP inbuilt function used to bind a parameter to the specified variable name in a sql statement for access the database record. bindValue, on the other hand, is again a PHP inbuilt function used to bind the value of parameter to the specified variable name in sql statement.

How do I SELECT in PDO?

SELECT query without parameters If there are no variables going to be used in the query, we can use a conventional query() method instead of prepare and execute. $stmt = $pdo->query("SELECT * FROM users"); This will give us an $stmt object that can be used to fetch the actual rows.

What are bound parameters?

A parameter binding is a piece of information that is transmitted from the origin to the destination of a flow. A parameter binding has a name and a value, which is obtained at its origin component. A flow may have a multiple parameter binding, passing a set of values instead of a single one.


2 Answers

You can't bind a parameter for the IN clause like that. The $myArray string will only count as one value, like if you did this:

SELECT foo FROM bar WHERE ids IN ('1,2,3')

Even though there are three comma delimited values, the database reads them as only one string value.

You need to manually insert the IN list into the query, the old-school way.

'SELECT foo FROM bar WHERE ids IN (' . $myArray .')'

There is unfortunately no other way. At least for now.

like image 111
Atli Avatar answered Oct 22 '22 14:10

Atli


I know this question is old, but this works for me:

$arrayOfValues = array(1,2,3,4,5);
$questionMarks = join(",", array_pad(array(), count($arrayOfValues), "?"));
$stmt = $dbh->prepare("update some_table set end_date = today where value_no in ($questionMarks)");
$stmt->execute($arrayOfValues);
like image 11
gusknows Avatar answered Oct 22 '22 14:10

gusknows