MySQLi prepared statement with dynamic update query

后端 未结 1 1394
终归单人心
终归单人心 2021-01-03 16:41

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

相关标签:
1条回答
  • 2021-01-03 16:54

    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.

    0 讨论(0)
提交回复
热议问题