Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

php - Proper format for PDO and MySQL IN/NOT IN queries

For reasons that should be obvious, this is murder to search for...

How do I do this in PDO:

SELECT thing FROM things WHERE thing_uid IN ( ... )

My particular use case is a string built by exploding an array taken from a form with several dozen checkboxes. In standard MySQL this is very easy...

$thingString = implode("', '", $thingArray);
$q = "SELECT thing FROM things WHERE thing_uid IN ('$thingString')";

but I want that to benefit from PDO's anti-injection protection... bound params and all that. So how can I do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create an array of as many ? as you have values, and throw that into the query.

$placeholders = array_fill(0, count($thingArray), '?');
$sql = "SELECT thing FROM things WHERE thing_uid IN (" . implode(',', $placeholders) . ")";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...