Home  >  Article  >  Database  >  Why Does PDO Return Only One Row When Binding Parameters to a WHERE IN Clause?

Why Does PDO Return Only One Row When Binding Parameters to a WHERE IN Clause?

DDD
DDDOriginal
2024-11-25 09:19:11781browse

Why Does PDO Return Only One Row When Binding Parameters to a WHERE IN Clause?

Binding WHERE IN Clause Parameters with PDO

Question:

When attempting to bind parameters to a WHERE IN clause using PDO, the resulting count is always one, unlike when manually inserting values without parametrization. What is the cause of this discrepancy?

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();

Answer:

Unfortunately, PHP Data Objects (PDO) does not support binding parameters for IN clauses directly. The $myArray array is treated as a single string, similar to this SQL:

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

Despite the presence of multiple comma-separated values, the database interprets them as one string value.

To achieve the desired behavior, the IN clauses must be manually inserted into the query as follows:

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

Unfortunately, there is no alternative mechanism for parameter binding in PDO's IN clauses at this time.

The above is the detailed content of Why Does PDO Return Only One Row When Binding Parameters to a WHERE IN Clause?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn