سؤال

I came across this tonight and found a few different posts about it here on SO, however, I cannot seem to get this working. The problem lies with the IN() clause and the fact I am using PDO prepared statements.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number' in /test.php:119 Stack trace: #0 /test.php(119): PDOStatement->execute(Array) #1 {main} thrown in /test.php on line 119

... it would be inserting the following into the clause and execute...

IN(?, ?, ?, ?, ?, ?)

and

$stmt->execute(array($_SESSION['user']['account_id'], 1, 2, 3, 4, 5, 6 ));

$selected = array(1, 2, 3, 4, 5, 6);
echo implode(', ', array_fill(1,count($selected),'?'));
echo implode(', ', $selected);

$stmt = $db->prepare("
    SELECT files.image_filename
    FROM files
        LEFT JOIN users
            on users.user_id = files.user_id
        LEFT JOIN computers
            on computers.computer_id = users.computer_id
        LEFT JOIN accounts
            on accounts.account_id = computers.account_id
    WHERE accounts.account_id = ? AND computers.computer_id IN(". implode(', ', array_fill(1,count($selected),'?')) .") 
");

$stmt->execute(array($_SESSION['user']['account_id'], implode(', ', $selected) ));

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

EDIT: I also should add if I manually enter the numbers this example it works as expected :

$stmt->execute(array($_SESSION['user']['account_id'], 1, 2, 3, 4, 5, 6));

EDIT:

as I mentioned in the op, but here is the output again:

?, ?, ?, ?, ?, ?
1, 2, 3, 4, 5, 6

هل كانت مفيدة؟

المحلول

You should change

$stmt->execute(array($_SESSION['user']['account_id'], implode(', ', $selected) ));

into

$stmt->execute(array_merge(array($_SESSION['user']['account_id']), $selected));

In your code you created array of 2 elements - probably id and string created from implode

Alternative solution is adding before this line:

array_unshift($selected, $_SESSION['user']['account_id']);

and then

$stmt->execute($selected);

In this case you of course modify $selected array. You may want to create copy of it if you need.

نصائح أخرى

You are using 6 x ? in SQL statement, while binding single string of 6 values joined by ,.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top