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
I think this is what you are looking for:
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
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.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 becomesss
. 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: