note 110176 added to pdostatement.bindparam
| From: | pascal dot poncet at netconsult dot com | Date: | Thu, 27 Sep 2012 00:20:06 +0000 |
| Subject: | note 110176 added to pdostatement.bindparam | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-191035@lists.php.net to get a copy of this message | ||
It can be confuse how to bind parameters in an SQL statement containing the special "IN"
comparison operator.
SQL example:
SELECT * FROM city WHERE region_id IN (10, 12, 14)
where values inside parenthesis might be variable, eg. enclosed in an array.
Here is my solution, even if many others should be possible.
The key idea is to build a string, in our example ":k1, :k2, :k3", that will be binded
with our array of values.
<?php
// suppose we have an array retrieved from client-side
$client_side_choices = array (10, 12, 14);
// first we build placeholder/value couples from the original array
foreach ($client_side_choices as $index => $value) {
$parameters[":k{$index}"] = $value;
}
// then build the string for placeholders
$placeholders = array_keys($parameters);
$placeholders_string = implode(', ', $placeholders);
// then instantiate PDO and prepare query
$db = new PDO(...);
$stmt = $db->prepare("
SELECT * FROM city
WHERE region_id IN ({$placeholders_string})
");
// finally, bind each parameter value and execute
foreach ($parameters as $key => $value) {
$stmt->bindParam($key, $value);
}
$stmt->execute();
?>
Hope this help,
Pascal
----
Server IP: 69.147.83.199
Probable Submitter: 78.114.114.122
----
Manual Page -- http://www.php.net/manual/en/pdostatement.bindparam.php
Edit -- https://master.php.net/note/edit/110176
Del: integrated -- https://master.php.net/note/delete/110176/integrated
Del: useless -- https://master.php.net/note/delete/110176/useless
Del: bad code -- https://master.php.net/note/delete/110176/bad+code
Del: spam -- https://master.php.net/note/delete/110176/spam
Del: non-english -- https://master.php.net/note/delete/110176/non-english
Del: in docs -- https://master.php.net/note/delete/110176/in+docs
Del: other reasons-- https://master.php.net/note/delete/110176
Reject -- https://master.php.net/note/reject/110176
Search -- https://master.php.net/manage/user-notes.php