note 110176 deleted from pdostatement.bindparam by googleguy

From: Date: Thu, 27 Sep 2012 01:17:57 +0000
Subject: note 110176 deleted from pdostatement.bindparam by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191037@lists.php.net to get a copy of this message
Note Submitter: pascal dot poncet at netconsult dot com ---- 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

« previous php.notes (#191037) next »