note 109256 added to mysqli-stmt.bind-param

From: Date: Sat, 30 Jun 2012 10:12:06 +0000
Subject: note 109256 added to mysqli-stmt.bind-param
Groups: php.notes 
Request: Send a blank email to php-notes+get-188976@lists.php.net to get a copy of this message
When dealing with a dynamic number of field values while preparing a statement I find this class useful. <?php class BindParam{ private $values = array(), $types = ''; public function add( $type, $value ){ $this->values[] = $value; $this->types .= $type; } public function get(){ return array_merge(array($this->types), $this->values); } } ?> Usage is pretty simple. Create an instance and use the add method to populate. When you're ready to execute simply use the get method. <?php $bindParam = new BindParam(); $qArray = array(); $use_part_1 = 1; $use_part_2 = 1; $use_part_3 = 1; $query = 'SELECT * FROM users WHERE '; if($use_part_1){ $qArray[] = 'hair_color = ?'; $bindParam->add('s', 'red'); } if($use_part_2){ $qArray[] = 'age = ?'; $bindParam->add('i', 25); } if($use_part_3){ $qArray[] = 'balance = ?'; $bindParam->add('d', 50.00); } $query .= implode(' OR ', $qArray); //call_user_func_array( array($stm, 'bind_param'), $bindParam->get()); echo $query . '<br/>'; var_dump($bindParam->get()); ?> This gets you the result that looks something like this: SELECT * FROM users WHERE hair_color = ? OR age = ? OR balance = ? array(4) { [0]=> string(3) "sid" [1]=> string(3) "red" [2]=> int(25) [3]=> float(50) } ---- Server IP: 69.147.83.197 Probable Submitter: 71.192.16.192 ---- Manual Page -- http://www.php.net/manual/en/mysqli-stmt.bind-param.php Edit -- https://master.php.net/note/edit/109256 Del: integrated -- https://master.php.net/note/delete/109256/integrated Del: useless -- https://master.php.net/note/delete/109256/useless Del: bad code -- https://master.php.net/note/delete/109256/bad+code Del: spam -- https://master.php.net/note/delete/109256/spam Del: non-english -- https://master.php.net/note/delete/109256/non-english Del: in docs -- https://master.php.net/note/delete/109256/in+docs Del: other reasons-- https://master.php.net/note/delete/109256 Reject -- https://master.php.net/note/reject/109256 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188976) next »