1

I have the following code in php to query the database based on an array sent by the client.

$limit = $_POST['limit'];
$userArray = json_decode($_POST['arr'], true);
$queryPlaceholders= implode(',', array_fill(0,count($userArray), '?'));
$stmt = $db->prepare("SELECT * FROM tableA
                          WHERE tableA.id IN (".$queryPlaceholders.")
                          LIMIT ?");
foreach($userArray as $k => $val){
    $stmt->bindParam(($k+1), $val);
}
$stmt->bindValue(count($userArray) + 1, (int)trim($limit), PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $result;

This code appears to have an error. If I send an array containing the values 11 & 17, the query seems to only run with the value 17, not both 11 and 17.

If I print_r($userArray) I get Array ( [0] => 11 [1] => 17 )

so I know php has the correct array. However, running this query with the code above, and running the query below yields different answers:

SELECT * FROM tableA
WHERE tableA.id IN (11,17)
LIMIT 10

When running the code above, It appears to infact run this query?

SELECT * FROM tableA
WHERE tableA.id IN (17)
LIMIT 10

I've also placed statements in the foreach loop that tells me both elements of the array (11 & 17) are being bound to the $stmt

1 Answer 1

3

The problem is that you are using bindParam():

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

Since $val is changed on each iteration of the foreach loop, it ultimately is the same for each placeholder when the query is finally executed.

Sign up to request clarification or add additional context in comments.

Comments

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.