简体   繁体   中英

PHP - MySQL prepared statement to INSERT an array

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 = array('column1' => 'value1', 'column2' => 'value2', 'column3' => 'value3')

I have this so far but I need help with the bind_param portion. I've seen documentation on here where call_user_func_array is used but I'm not sure how to implement this.

$cols = array_keys($insert);
$query = "INSERT IGNORE INTO results (". implode(", ", $cols) .") VALUES (". implode(', ', array_fill(0, count($insert), '?')) .")";
$stmt = $mysqli->prepare($query);
$param = array_merge(array(str_repeat('s', count($insert))), array_values($insert)); 
call_user_func_array(array($stmt, 'bind_param'), $param); 
$stmt->execute();

PHP 5.4.17

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

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); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM