/    Sign up×
Community /Pin to ProfileBookmark

PDO SELECT WHERE IN (ARRAY)

Final question / issue with this.

I don’t believe this is possible but I’ll throw it out there.

I have an array of ID’s being submitted by a user. Is it possible to do sometihng like

[code]
WHERE `studentId` IN(:IDS)
[/code]

Where IDS = implode(“,”, $_POST[students’]);

From testing it binds it into the query as a string which only matches against the first value.


—-

If nothing is possible. Given I need to do this against several fields. It is better to retrieve ALL records from my database and do PHP filtration. However I may have over 7,000 rows in my database shortly.

to post a comment
PHP

17 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmNov 01.2021 — Actually I already answered that in your earlier post
Copy linkTweet thisAlerts:
@kiwisauthorNov 01.2021 — @ginerjm#1638931

Why post was that? the one about dates?
Copy linkTweet thisAlerts:
@ginerjmNov 01.2021 — How many active ones do you have?
Copy linkTweet thisAlerts:
@kiwisauthorNov 01.2021 — @ginerjm#1638933 Is that a trick question? I'm unsure if you're actually here to help or not?

There's several topics that I see as unrelated as I do this very much part time and always google things first. If there's an overlap or same answer to different issues as I see it. Please just point it out.
Copy linkTweet thisAlerts:
@ginerjmNov 01.2021 — You cannot use an array as a :arg in a prepared query. You must figure out how to create a group of vars instead of :IDS That's why you got that error you posted in your previous query.

And please don't tell me you are one of those annoying posters who have 10 things going at the same time and don't pay attention to what people tell them because they have too much going on.
Copy linkTweet thisAlerts:
@kiwisauthorNov 01.2021 — @ginerjm#1638936

Right, you're reply to this

https://www.webdeveloper.com/d/397540-pdostatementexecute-sqlstatehy093-invalid-parameter-number/2

Which I had solved prior to your reply so didn't actually go back at see the response in full. Some forums marks threads as solved.

I've googled this and can't see a solution. Does one actually exist, all I've found is that it's a limitation to PDO and use other Database's or work arounds outside of the query.
Copy linkTweet thisAlerts:
@ginerjmNov 01.2021 — You could probably do it with variable variables and doing a loop on the array of values that you have. Something for you to focus on and solve for yourself. I'm not going to try.

And PS - your last post on that topic was a question so I'm surprised that you are now saying that it was solved. Too much going on??
Copy linkTweet thisAlerts:
@NogDogNov 01.2021 — Yeah, PDO (or probably any other DB abstraction layer of the same sort) is not going to automagically handle that. You'll probably have to just take that array and turn it into a comma-separated list, doing your own validation/escaping of the user-supplied data. If it's just integer values, maybe something like
[code=php]
$ids = [];
foreach($_POST['students'] as $id) {
$ids[] = (int) $id;
}
$where_clause = "WHERE studentId IN(".implode(',', $ids).")";
[/code]
Copy linkTweet thisAlerts:
@kiwisauthorNov 02.2021 — @NogDog#1638939

Cheers, isn't this approach open to thngs like SQL injection etc?
Copy linkTweet thisAlerts:
@NogDogNov 02.2021 — @kiwis80#1638942

That's the purpose of the foreach loop in my example: every value will be explicitly set to an integer, so if someone tries to include something like "1 or (truncate table students)", the casting of it to an integer will (in this crude example) convert it to integer 1.
Copy linkTweet thisAlerts:
@SempervivumNov 02.2021 — Not being a database expert I figured out this solution:
``<i>
</i>include 'connect.php';
$_POST['years'] = [1903, 1912, 1952, 1977];
$placeholders = implode(',', array_fill(0, count($_POST['years']), '?'));
$sql = "select title, year from movie where year in($placeholders)";
$statement = $pdo-&gt;prepare($sql);
$result = $statement-&gt;execute($_POST['years']);
var_dump($statement-&gt;fetchAll());<i>
</i>
``

(used a table I had on hand)

How would you rate it?
Copy linkTweet thisAlerts:
@kiwisauthorNov 02.2021 — @Sempervivum#1638944

Cheers. I've never used array_fill before. Whats the logic in the ? on the 3rd paramter?
Copy linkTweet thisAlerts:
@SempervivumNov 02.2021 — Just read the manual:

https://www.php.net/manual/en/function.array-fill.php

It will create an array of a given size where all values are the same (third parameter '?' here).
Copy linkTweet thisAlerts:
@kiwisauthorNov 02.2021 — @ginerjm#1638938

I'm confused why you're participating in a support forum based on the tone of your replies.

Like I've said on the other thread - I figured out what the other user was referring to then got busy with my other "real job" and forgot to update the thread.
Copy linkTweet thisAlerts:
@kiwisauthorNov 02.2021 — @Sempervivum#1638946

When I looked at this it says..

"value

Value to use for filling"

Genuine question, how would/should I know a ? does this?
Copy linkTweet thisAlerts:
@SempervivumNov 02.2021 — The intention is to create a string containing the placeholders like this: '?,?,?' By dumping the variable $placeholders you can verify that it does. And when I dump the statement the result is:

'select title, year from movie where year in(?,?,?,?)'

where the number of placeholders equals the number of POST parameters.
Copy linkTweet thisAlerts:
@NogDogNov 02.2021 — Okay, this _might_ work, but I have not actually tested it against a database/connection, so.... 🤷 (Note use of &amp; where I'm passing variables by reference instead of value -- not sure if this is actually needed, so you could try without it if you want. :) )
[code=php]
$_POST['students'] = [11, 13, 12, 15, 14];
$_POST['foo'] = 'bar';

$sql = "
SELECT *
FROM some_table
WHERE foo = :foo
";

$bind_values = [':foo' => &$_POST['foo']];

if(!empty($_POST['students']) and is_array($_POST['students'])) {
$counter = 1;
$student_ids = [];
foreach ($_POST['students'] as $student_id) {
${"student_id_$counter"} = $student_id;
$student_ids[":student_id_$counter"] = &${"student_id_$counter"};
$counter++;
}
$sql .= "AND id IN(".implode(',', array_keys($student_ids)).")n";
$bind_values = array_merge($bind_values, $student_ids);
}

$sql .= "ORDER BY some_column";

/* USAGE:
$stmt = $pdo->prepare($sql);
$stmt->execute($bind_values);
*/

// debug output:
echo "$sqln";
var_dump($bind_values);
[/code]

Test output:
[code=text]
SELECT *
FROM some_table
WHERE foo = :foo
AND id IN(:student_id_1,:student_id_2,:student_id_3,:student_id_4,:student_id_5)
ORDER BY some_column
array(6) {
[":foo"]=>
&string(3) "bar"
[":student_id_1"]=>
&int(11)
[":student_id_2"]=>
&int(13)
[":student_id_3"]=>
&int(12)
[":student_id_4"]=>
&int(15)
[":student_id_5"]=>
&int(14)
}
[/code]
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...