MySQLI binding params using call_user_func_array

后端 未结 7 2311
别跟我提以往
别跟我提以往 2020-11-30 09:01

Please see below my code. I am attempting to bind an array of paramenters to my prepared statement. I\'ve been looking around on the web and can see I have to use call_user_

7条回答
  •  Happy的楠姐
    2020-11-30 09:34

    Most of the above are not solutions without integrating the types along with the values before adding them to call_user_func_array(). This solution worked for me:

    /* create a database connection */
    $db = new mysqli($host, $user, $password, $db_name);
    
    /* setup the sql, values, and types */
    $sql="SELECT * FROM languages 
             WHERE language_code = ?
               AND charset = ?
             ORDER BY native_name";
    $values = array($langCode, $charset);
    $types = "ss";   
    
    /* pass those variables to the execute() function defined below */
    if ($rows = execute($sql, $values, $types))
    {
       return $rows[0];
    }
    
    function execute($sql, $values='', $types='')
    {
       /* prepare the sql before binding values and types */
       $stmt = $db->prepare($sql);
    
       /*combine the values and types into $inputArray */
       $inputArray[] = &$types;
       $j = count($values);
       for($i=0;$i<$j;$i++){
         $inputArray[] = &$values[$i];
       }
       /* add the combined values and types to call_user_func_array() for binding */
       call_user_func_array(array($stmt, 'bind_param'), $inputArray);
       $result = $stmt->execute();
       return $result;
    }
    

    Here's a reference to the full description this example is based on: http://big.info/2015/08/php-use-call_user_func_array-for-variable-number-of-parameters-arrays-in-prepared-statements.html

提交回复
热议问题