I\'m busy changing from normal mysql_queries to prepared statements, now I found a function that generated a dynamic query based on how many fields were not empty.
I
The trick is to construct an array that contains the parameters that you want to bind, then with the help of call_user_func_array
, you can pass this array to bind_param
.
See http://www.php.net/manual/en/function.call-user-func-array.php for details on call_user_func_array
.
Your code can be something like:
$para_type="";
/* $para is the array that later passed into bind_param */
$para=array($para_type);
$query = 'UPDATE tickets SET ';
IF(count($data) != 0) {
/* Looping all values */
foreach($data as $k=>$d) {
$query .= '`'.$d['field'].'` = ? ,';
$para_type .=$d['type'];
$para[] = &$data[$k]['value'];
}
/* removing last comma */
$query[(strlen($query)-2)] = '';
/* adding where */
$query .= ' WHERE `ticket_id` = ?';
$para_type .= 'i';
$para[]=&$ticket_id;
call_user_func_array(array($stmt, 'bind_param'), $para);
return true;
}
Notice the &
in front of all parameters, it is required by bind_param
.
Another way which I think is better is to use PDO. It takes named parameter and can do incremental bind.