PHP - MySQL prepared statement to INSERT an array

后端 未结 3 846
暖寄归人
暖寄归人 2021-01-15 02:45

I\'m editing a script that is using MySQLi. I need to use prepared statement to insert some values into the db.

My array is in the form of:

$insert =         


        
相关标签:
3条回答
  • 2021-01-15 03:18

    No... this was definitely harder than PDO with any array because of how mysqli_stmt_bind_param() works... and this works fine by changing $array to removing/adding data for other columns.

    $mysqli = new mysqli('localhost', 'root', 'password', 'test');
    
    $array  = array("name"=>"pineapple", "color"=>"purple"); 
    
    $table_name = "fruit"; 
    
    
    
    insert_data($mysqli, $array, $table_name);
    
    
    
    function insert_data($mysqli, $array, $table_name) 
    {
       $placeholders = array_fill(0, count($array), '?');
    
       $keys   = array(); 
       $values = array();
       foreach($array as $k => $v) {
          $keys[] = $k;
          $values[] = !empty($v) ? $v : null;
       }
    
       $query = "insert into $table_name ".
                '('.implode(', ', $keys).') values '.
                '('.implode(', ', $placeholders).'); '; 
       // insert into fruit (name, color) values (?, ?);    
    
       $stmt = $mysqli->prepare($query);
    
       // create a by reference array... 
       $params = array(); 
       foreach ($array as &$value) { 
          $params[] = &$value;
       }
       $types  = array(str_repeat('s', count($params))); 
       $values = array_merge($types, $params); 
    
       /*           
       $values = Array
          (
              [0] => ss
              [1] => pineapple
              [2] => purple
          ) 
       */
    
       call_user_func_array(array($stmt, 'bind_param'), $values); 
    
       $success = $stmt->execute();
    
       if ($success) { print "it worked..."; } 
               else { print "it did not work..."; }
    }  
    

    I got some help from these SO posts:
    - https://stackoverflow.com/a/15933696/623952
    - https://stackoverflow.com/a/6179049/623952


    So... in $stmt->bind_param() the first parameter is a string that has one char for each parameter passed in. And that char represents the parameter data type. In the example above, both of the two parameters are strings so it becomes ss. A string is always assumed in the example above, too.

    I found this chart in the bind_param() documentation:

    types
    A string that contains one or more characters which specify the types for the corresponding bind variables:

    Type specification chars  
    
    Character    Description  
    i            corresponding variable has type integer
    d            corresponding variable has type double
    s            corresponding variable has type string
    b            corresponding variable is a blob and will be sent in packets
    
    0 讨论(0)
  • 2021-01-15 03:25

    I think this is what you are looking for:

    cols = array_keys($insert);
    $query = "INSERT INTO results (". implode(", ", $cols) .") VALUES (". str_repeat('?', count($insert)) .")";
    $stmt = $mysqli->prepare($query);
    
    call_user_func_array('mysqli_stmt_bind_param', array_merge (array($stmt, str_repeat('s', count($insert))), $insert); 
    
    0 讨论(0)
  • 2021-01-15 03:25

    inserting arrays with bind_param is painful, i recommend to use php's filter_var function. it does same filtering and also validates variables, inputs, its perfect. function manual page

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