Mysqli bind param update - php

I just started creating mysqli bind_param update function. My insert function works fine, but there i get error - Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables. I dont get where is the problem.
My array = Array ( [bday_month] => 9 [bday_day] => 7 [bday_year] => 2003 [id] => 2 )
public function update($table, $data) {
if (empty($table) || empty($data)) {
return false;
}
$array_slice = array_slice($data, 0, count($data)-1);
$fields = implode(' = ?, ', array_keys($array_slice)) . ' = ?';
$stmt = $this->db->prepare("UPDATE `{$table}` SET {$fields} WHERE `id` = ?");
call_user_func_array(array($stmt, 'bind_param'), $this->refValues($data));
$stmt->execute();
}

Solved. I forget insert types.

i have this one worked for me you could see it
/**
* update
* #author Alaa M. Jaddou
* #param string $table A name of table to insert into
* #param string $data An associative array
* #param string $where the WHERE query part
*/
public function update($table, $data, $where)
{
ksort($data);
$fieldDetails = NULL;
foreach($data as $key=> $value) {
$fieldDetails .= "`$key`= ?,";
}
$fieldDetails = rtrim($fieldDetails, ',');
$sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");
$values = array();
foreach ($data as $key => $value) {
$values = implode(', ', $value);
}
$sth->bind_param($values);
return $sth->execute();
}

Related

HOW TO LOOP PHP'S PDO BIND PARAM

Im current creating my own query builder now and Im stuck with PDO's prepared statement. Isn't it possible to loop the the PDO's BindParam. I did it using foreach() but it's not working it only on works on the last data that the loop executed.
$sql = "SELECT * FROM users WHERE id = :a OR fname = :b";
$array = array(":a"=>"10002345", "Josh");
$stmt = $conn->prepare($sql);
foreach($array as $key => $value ) {
$stmt->bindParam($key, $value);
}
$stmt->execute();
it only binds the last data executed by the loop.
It is better to use ? placeholders in a query and pass array of data to execute:
$sql = "SELECT * FROM users WHERE id = ? OR fname = ?";
$array = array("10002345", "Josh"); // you don't even need keys here
$stmt = $conn->prepare($sql);
$stmt->execute($array);
Only just stumbled across this, but just for future reference...
Firstly, I'll work on the assumption that your example was supposed to read $array = array(":a"=>"10002345", ":b"=>"Josh");, as there would be an issue even if your :b key was absent.
In this bit:
foreach($array as $key => $value ) {
$stmt->bindParam($key, $value);
}
You haven't 'passed by reference'. The $value should be amended to &$value
foreach($array as $key => &$value ) {
$stmt->bindParam($key, $value);
}
This is because the bindParam method signature requires the value to be a variable reference:
public function bindParam ($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) {}
(note the & before $variable).
The end result of your original query (sans &) is that all :params would be set to the value that is in the last iteration of $value in your original loop.
So, the result of
$sql = "SELECT * FROM users WHERE id = :a OR fname = :b";
$array = array(":a"=>"10002345", ":b"=>"Josh");
$stmt = $conn->prepare($sql);
foreach($array as $key => $value ) {
$stmt->bindParam($key, $value);
}
$stmt->execute();
Would be SELECT * FROM users WHERE id = 'Josh' OR fname = 'Josh'
Using named parameters (:param) has advantages over positional params (?), so it's worth reserving that option for prepared statements, as opposed to the accepted answer of "it's better to use ? placeholders", which is not the case.
In my database abstraction layer I use the following utility functions:
/**
* getFieldList return the list with or without PK column
* #param bool $withID - true when including parameter
*/
static protected function getFieldList( $withID = false )
{
if( $withID )
$result = '`' . static::getTableName( ) . '`' .
'.`' . static::getPrimaryKeyName( ) . '`, ';
else
$result = '';
return $result .= '`' . static::getTableName( ) . '`.' .
'`' . implode( '`, `'.static::getTableName( ) . '`.`', static::getFieldNames( ) ) . '`';
}
/**
* getFieldPlaceholders -
* #return string - all PDO place holders prefixed :
*/
static protected function getFieldPlacholders( )
{
return ':' . implode( ',:', static::getFieldNames( ) );
}
/**
* getUpdateList - SQL updates section
* #return string
*/
static private function getUpdateList( )
{
$result = array( );
foreach( static::getFieldNames( ) as $field ) {
if( $field === static::getPrimaryKeyName() ) continue;
$result[] = '`' . $field . '`=:' . $field;
}
return implode( ',', $result );
}
/**
* Bind the fields to PDO placeholdes
* #param PDOStatement $stmt statement that the fields are bound to
* #return void
*/
protected function bindFields( $stmt )
{
foreach( array_keys($this->fields) as $field ) {
if( $field === static::getPrimaryKeyName() ) continue;
$stmt->bindParam( ':' . $field, $this->fields[$field] );
// echo $field . '->' . $this->fields[$field] . '<br>';
}
}
/**
* Bind the fields to the placeholders
* #param PDOStatement $stmt - that the fields are bind to
* #return void
*/
protected function bindColumns( $stmt, $withID = false )
{
if( $withID )
$stmt->bindColumn( static::getPrimaryKeyName(), $this->ID );
foreach( static::getFieldNames() as $fieldname )
{
$stmt->bindColumn( $fieldname, $this->fields[$fieldname] );
}
}
/**
* parseResultset
* Set the values of the select results, resets dirty (object is in sync)
* #param mixed[] $result - associative array
*/
protected function parseResultset( $result )
{
foreach( $result as $field=> $value ) {
if( $field === static::getPrimaryKeyName() )
$this->ID = $value;
$this->fields[$field] = $value;
}
$this->dirty = array();
}

Incorrect datetime value: '2018' for column when passing valid date as string

Today i experience a very strange issue. Appearently the date passed is not the same as the one bind_param passes to my query.
The database structure:
|id varchar(16) autoincrement|date_created datetime|date_updated datetime|
Currently the table contains valid data:
|1|2018-01-25 16:53:40|2018-01-25 16:53:40|
Now i am trying to execute a prepared UPDATE statement:
UPDATE `table1` SET `date_created` = ?, `date_updated` = ? WHERE `id` = ?
and i am binding following data:
["date_created"]=> string(19) "2018-01-25 16:53:40"
["date_updated"]=> string(19) "2018-01-25 17:02:57"
["id"]=> int(1) 1
but for any reason i get the error
1292: string(67) "Incorrect datetime value: '2018' for column 'date_created' at row 1"
I do not understand why bind_params or execute should cut down the valid date to just the year
EDIT: The PHP code, as requested. It is a function that automatically generates the query and executes it. I added a part that var_dumps the "should be executed" query
public function executeUpdateQuery(){
// update existing record
$where['id'] = 1;
$array['date_created'] = self::getTimeStamp();
$array['date_updated'] = self::getTimeStamp();
if(!$this->updateRecord($where, $array)){
print("<br>Error:<br>");
var_dump($this->db->error);
}
}
public static function getTimeStamp(){
return date('Y-m-d H:i:s');
}
/**
* #param array $array
* #return string
*/
public static function getTypes(array $array = []) : string {
$types = "";
foreach ($array as $value){
if(is_int($value))
$types .= "i";
elseif(is_string($value))
$types .= "s";
elseif(is_bool($value))
$types .= "i";
else
$types .= "s";
}
return $types;
}
public function updateRecord(array $array = [], array $fields = []){
if(empty($array) || empty($fields)) return FALSE;
/** #var \mysqli_stmt $stmt */
$query = "UPDATE `" . $this->tablename . "` SET `" . implode("` = ?, `", array_keys($fields)) . "` = ? WHERE `" . implode("` = ? AND `", array_keys($array)) . "` = ?;";
$stmt = $this->db->prepare($query);
$types = self::getTypes($fields);
$types .= self::getTypes($array);
if(!$stmt->bind_param($types, ...array_values($fields), ...array_values($array))) {
return FALSE;
}
$result = $stmt->execute();
$resultquery = $query;
foreach ($fields as $field){
$resultquery = $this->str_replace_first('?', (is_int($field)?$field:"'".$field."'"), $resultquery);
}
foreach ($array as $field){
$resultquery = $this->str_replace_first('?', (is_int($field)?$field:"'".$field."'"), $resultquery);
}
var_dump($resultquery);
print("<br>Fields:<br>");
var_dump($fields);
print("<br>Affected Rows:<br>");
var_dump(mysqli_affected_rows($this->db));
print("<br>Errors:<br>");
var_dump(mysqli_errno($this->db));
var_dump(mysqli_error($this->db));
var_dump(mysqli_error_list($this->db));
return $result;
}
public function str_replace_first($from, $to, $subject){
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $subject, 1);
}
Appearently the issue was that the datetime field was bound as integer instead of a string, because i mixed up these 2 arrays:
$types = self::getTypes($fields);
$types .= self::getTypes($array);
Due to that, the string "2018-01-25 16:53:40" was casted into the integer 2018
The actually executed bind_param that was executed looked like:
bind_param(iss, a string, a string, an integer);

Build a single multiple insert query from an array in PHP

I have an array that looks like this
$users = array(
array('name'=>'aaa','age'=>2),
array('name'=>'bbb','age'=>9),
array('name'=>'ccc','age'=>7)
);
I would like to create a function that will accept an array like above, creates a clause for a single query-multiple insert, prepares an array of variable that I can bind with PDO.
example output:
$clause = INSERT INTO tablename (`name`,`age`)
VALUES (:name_0,:age_0),(:name_1,:age_1),(:name_2,:age_2);
Then another set of array corresponding to the values above:
$params => Array
(
[name_0] => aaa
[age_0] => 2
[name_1] => bbb
[age_1] => 9
[name_2] => ccc
[age_2] => 7
);
So that the can execute it like so:
$prepared = $connection->prepare($clause);
$prepared->execute($params);
Is it possible to achieve this in a single function?
Yes that very possible, I did exactly the same thing for my custom query builder class:
function INSERT_MULTIPLE_QUERY($ARRS = array()){
$raw_cols = '(`';
// PREPARE THE COLUMNS
foreach($ARRS[0] as $key1 => $value):
$raw_cols .= $key1.'`,`';
endforeach;
$final_cols = rtrim($raw_cols,'`,`') . '`)';
$ctr1=0; $raw_vals='';
// PREPARE THE VALUES
foreach($ARRS as $ARR_VALUE):
$raw_vals .= '(';
foreach($ARR_VALUE as $key => $value): $raw_vals .= ':'.$key.'_'.$ctr1.','; endforeach;
$raw_vals = rtrim($raw_vals,',');
$raw_vals .= '),';
$ctr1++;
endforeach;
$final_vals = rtrim($raw_vals,',');
$ctr2 = 0; $param = array();
// PREPARE THE PARAMETERS
foreach($ARRS as $ARR_PARAM):
foreach($ARR_PARAM as $key_param => $value_param):$param[$key_param.'_'.$ctr2] = $value_param; endforeach;
$ctr2++;
endforeach;
// PREPARE THE CLAUSE
$clause = 'INSERT INTO tablename ' . $final_cols . ' VALUES ' . $final_vals;
// RETURN THE CLAUSE AND THE PARAMETERS
$return['clause'] = $clause;
$return['param'] = $param;
return $return;
}
Now to use this function:
$query = INSERT_MULTIPLE_QUERY($users);
// $users is your example array above
Then:
$prepared = $connection->prepare($query['clause']);
$prepared->execute($query['param']);
You can do it in a OOP style by creating a QueryBuilder and PDOStatementDecorator like below:
class QueryBuilder
{
const BUILD_TYPE_INSERT_MULTIPLE = 'INSERT_MULTIPLE';
protected $table;
protected $values;
protected $buildType;
public function __construct($table)
{
$this->table = $table;
}
public static function onTable($table)
{
return new self($table);
}
public function insertMultiple(Array $values = array())
{
$this->values = $values;
$this->buildType = self::BUILD_TYPE_INSERT_MULTIPLE;
return $this;
}
public function build()
{
switch ($this->buildType) {
case self::BUILD_TYPE_INSERT_MULTIPLE:
return $this->buildInsertMultiple();
}
}
protected function buildInsertMultiple()
{
$fields = array_keys($this->values[0]);
$query = "INSERT INTO {$this->table} (" . implode(',', $fields) . ") VALUES ";
$values = array();
for ($i = 0; $i < count($fields); $i++) {
$values[] = '(' . implode(', ', array_map(function($field) use ($i) {
return ':' . $field . $i;
}, $fields)) . ')';
}
$query .= implode(', ', $values);
return $query;
}
}
class PDOStatementDecorator
{
protected $pdoStatement;
public function __construct(PDOStatement $pdoStatement)
{
$this->pdoStatement = $pdoStatement;
}
public function executeMultiple(Array $bindsGroup = array())
{
$binds = array();
for ($i = 0; $i < count($bindsGroup); $i++) {
foreach ($bindsGroup[$i] as $key => $value) {
$binds[$key . $i] = $value;
}
}
return $this->execute($binds);
}
public function execute(Array $inputParemeters)
{
return $this->pdoStatement->execute($inputParemeters);
}
public function fetch($fetchStyle = null, $cursorOrientation = 'PDO::FETCH_ORI_NEXT', $cursorOffset = 0)
{
return $this->pdoStatement->fetch($fetchStyle, $cursorOrientation, $cursorOffset);
}
/**
* TODO
* Implement all public PDOStatement methods
*/
}
The query builder can be enhanced to be able to build queries for update/delete statements.
Now the usage would be very simple:
$users = array(
array('name' => 'aaa', 'age' => 2),
array('name' => 'bbb', 'age' => 9),
array('name' => 'ccc', 'age' => 7),
);
$query = QueryBuilder::onTable('users')->insertMultiple($users)->build();
$stmt = new PDOStatementDecorator($pdo->prepare($query));
$stmt->executeMultiple($users);
This function require Table Name, your original array, and an optional parameter that is used as default value, only if one field is not present in all array rows:
function buildQuery( $table, $array, $default='NULL' )
{
/* Retrieve complete field names list: */
$fields = array();
foreach( $array as $row ) $fields = array_merge( $fields, array_keys( $row ) );
$fields = array_unique( $fields );
/* Analize each array row, then update parameters and values chunks: */
$values = $params = array();
foreach( $array as $key => $row )
{
$line = array();
foreach( $fields as $field )
{
if( !isset( $row[$field] ) )
{ $line[] = $default; }
else
{
$line[] = ":{$field}_{$key}";
$params["{$field}_{$key}"] = $row[$field];
}
}
$values[] = '('.implode(',',$line).')';
}
/* Compone MySQL query: */
$clause = sprintf
(
"INSERT INTO `%s` (`%s`) VALUES %s;",
$table,
implode( '`,`', $fields ),
implode( ',', $values )
);
/* Return array[ clause, params ]: */
return compact( 'clause', 'params' );
}
Calling it in this way:
$query = buildQuery( 'mytable', $users );
$query will contain this:
Array
(
[clause] => INSERT INTO `mytable` (`name`,`age`) VALUES (:name_0,:age_0),(:name_1,:age_1),(:name_2,:age_2);
[params] => Array
(
[name_0] => aaa
[age_0] => 2
[name_1] => bbb
[age_1] => 9
[name_2] => ccc
[age_2] => 7
)
)
eval.in demo

Wordpress $wpdb. Insert Multiple Records

Is there any way to accomplish the following in Wordpress with $wpdb->insert or
$wpdb->query($wpdb->prepare)):
INSERT into TABLE (column1, column2, column3)
VALUES
('value1', 'value2', 'value3'),
('otherval1', 'otherval2', 'otherval3'),
('anotherval1', 'anotherval2', 'anotherval3')
...etc
OK, I figured it out!
Setup arrays for Actual Values, and Placeholders
$values = array();
$place_holders = array();
the initial Query:
$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";
Then loop through the the values you're looking to add, and insert them in the appropriate arrays:
foreach ( $_POST as $key => $value ) {
array_push( $values, $value, $order_id );
$place_holders[] = "('%d', '%d')" /* In my case, i know they will always be integers */
}
Then add these bits to the initial query:
$query .= implode( ', ', $place_holders );
$wpdb->query( $wpdb->prepare( "$query ", $values ) );
You can also use this way to build the query:
$values = array();
// We're preparing each DB item on it's own. Makes the code cleaner.
foreach ( $items as $key => $value ) {
$values[] = $wpdb->prepare( "(%d,%d)", $key, $value );
}
$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES ";
$query .= implode( ",\n", $values );
I have came across with this problem and decided to build a more improved function by using accepted answer too:
/**
* A method for inserting multiple rows into the specified table
*
* Usage Example:
*
* $insert_arrays = array();
* foreach($assets as $asset) {
*
* $insert_arrays[] = array(
* 'type' => "multiple_row_insert",
* 'status' => 1,
* 'name'=>$asset,
* 'added_date' => current_time( 'mysql' ),
* 'last_update' => current_time( 'mysql' ));
*
* }
*
* wp_insert_rows($insert_arrays);
*
*
* #param array $row_arrays
* #param string $wp_table_name
* #return false|int
*
* #author Ugur Mirza ZEYREK
* #source http://stackoverflow.com/a/12374838/1194797
*/
function wp_insert_rows($row_arrays = array(), $wp_table_name) {
global $wpdb;
$wp_table_name = esc_sql($wp_table_name);
// Setup arrays for Actual Values, and Placeholders
$values = array();
$place_holders = array();
$query = "";
$query_columns = "";
$query .= "INSERT INTO {$wp_table_name} (";
foreach($row_arrays as $count => $row_array)
{
foreach($row_array as $key => $value) {
if($count == 0) {
if($query_columns) {
$query_columns .= ",".$key."";
} else {
$query_columns .= "".$key."";
}
}
$values[] = $value;
if(is_numeric($value)) {
if(isset($place_holders[$count])) {
$place_holders[$count] .= ", '%d'";
} else {
$place_holders[$count] .= "( '%d'";
}
} else {
if(isset($place_holders[$count])) {
$place_holders[$count] .= ", '%s'";
} else {
$place_holders[$count] .= "( '%s'";
}
}
}
// mind closing the GAP
$place_holders[$count] .= ")";
}
$query .= " $query_columns ) VALUES ";
$query .= implode(', ', $place_holders);
if($wpdb->query($wpdb->prepare($query, $values))){
return true;
} else {
return false;
}
}
Source: https://github.com/mirzazeyrek/wp-multiple-insert
In addition to inserting multiple rows using $wpdb, if you ever need to update existing rows following snippet should be helpful.
This is updated snippet of what #philipp provided above.
$values = array();
// We're preparing each DB item on it's own. Makes the code cleaner.
foreach ( $items as $key => $value ) {
$values[] = $wpdb->prepare( "(%d,%d)", $key, $value );
}
$values = implode( ",\n", $values );
$query = "INSERT INTO orders (order_id, product_id, quantity) VALUES {$values} ON DUPLICATE KEY UPDATE `quantity` = VALUES(quantity)";
This is a bit late, but you could also do it like this.
global $wpdb;
$table_name = $wpdb->prefix . 'your_table';
foreach ($your_array as $key => $value) {
$result = $wpdb->insert(
$table_name,
array(
'colname_1' => $value[0],
'colname_2' => $value[1],
'colname_3' => $value[2],
)
);
}
if (!$result) {
print 'There was a error';
}
not very nice, but if you know what you are doing:
require_once('wp-load.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
#mysql_select_db(DB_NAME) or die();
mysql_query("INSERT into TABLE ('column1', 'column2', 'column3') VALUES
('value1', 'value2', 'value3'),
('otherval1', 'otherval2', 'otherval3'),
('anotherval1', 'anotherval2', 'anotherval3)");

Use one bind_param() with variable number of input vars

I try to use variable binding like this:
$stmt = $mysqli->prepare("UPDATE mytable SET myvar1=?, myvar2=... WHERE id = ?")) {
$stmt->bind_param("ss...", $_POST['myvar1'], $_POST['myvar2']...);
but some of the $_POST['...'] might be empty so I don't want to update them in the DB.
It's not practical to take into account all the different combination of empty $_POST['...'] and although I can build the string " UPDATE mytable SET..." to my needs, bind_param() is a different beast.
I could try building its call as a string and use eval() on it but it doesn't feel right :(
You could use the call_user_func_array function to call the bind_param method with a variable number or arguments:
$paramNames = array('myvar1', 'myvar2', /* ... */);
$params = array();
foreach ($paramNames as $name) {
if (isset($_POST[$name]) && $_POST[$name] != '') {
$params[$name] = $_POST[$name];
}
}
if (count($params)) {
$query = 'UPDATE mytable SET ';
foreach ($params as $name => $val) {
$query .= $name.'=?,';
}
$query = substr($query, 0, -1);
$query .= 'WHERE id = ?';
$stmt = $mysqli->prepare($query);
$params = array_merge(array(str_repeat('s', count($params))), array_values($params));
call_user_func_array(array(&$stmt, 'bind_param'), $params);
}
This is what I use to do mysqli prepared statements with a variable amount of params. It's part of a class I wrote. It propably is overkill for what you need but it should show you the right direction.
public function __construct($con, $query){
$this->con = $con;
$this->query = $query;
parent::__construct($con, $query);
//We check for errors:
if($this->con->error) throw new Exception($this->con->error);
}
protected static $allowed = array('d', 'i', 's', 'b'); //allowed types
protected static function mysqliContentType($value) {
if(is_string($value)) $type = 's';
elseif(is_float($value)) $type = 'd';
elseif(is_int($value)) $type = 'i';
else throw new Exception("type of '$value' is not string, int or float");
return $type;
}
//This function checks if a given string is an allowed mysqli content type for prepared statement (s, d, b, or i)
protected static function mysqliAllowedContentType($s){
return in_array($s, self::$allowed);
}
public function feed($params){
//These should all be empty in case this gets used multiple times
$this->paramArgs = array();
$this->typestring = '';
$this->params = $params;
$this->paramArgs[0] = '';
$i = 0;
foreach($this->params as $value){
//We check the type:
if(is_array($value)){
$temp = array_keys($value);
$type = $temp[0];
$this->params[$i] = $value[$type];
if(!self::mysqliAllowedContentType($type)){
$type = self::mysqliContentType($value[$type]);
}
}
else{
$type = self::mysqliContentType($value);
}
$this->typestring .= $type;
//We build the array of values we pass to the bind_params function
//We add a refrence to the value of the array to the array we will pass to the call_user_func_array function. Thus say we have the following
//$this->params array:
//$this->params[0] = 'foo';
//$this->params[1] = 4;
//$this->paramArgs will become:
//$this->paramArgs[0] = 'si'; //Typestring
//$this->paramArgs[1] = &$this->params[0];
//$this->paramArgs[2] = &$this->params[1].
//Thus using call_user_func_array will call $this->bind_param() (which is inherented from the mysqli_stmt class) like this:
//$this->bind_param( 'si', &$this->params[0], &$this->params[1] );
$this->paramArgs[] = &$this->params[$i];
$i++;
}
unset($i);
$this->paramArgs[0] = $this->typestring;
return call_user_func_array(array(&$this, 'bind_param'), $this->paramArgs);
}
You use it like this:
$prep = new theClassAboveHere( $mysqli, $query );
$prep->feed( array('string', 1, array('b', 'BLOB DATA') );
The class should extend the mysqli_stmt class.
I hope this helps you in the right direction.
If you wan't I could also post the whole class, it includes variable results binding.
It is marginally more clear to build your statement using an array:
$params = array();
$fragments = array();
foreach($_POST as $col => $val)
{
$fragments[] = "{$col} = ?";
$params[] = $val;
}
$sql = sprintf("UPDATE sometable SET %s", implode(", ", $fragments));
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($params);
array_insert does not exist, i'm guessing he refers to some home made function, but i'm not sure exactly what it does ... inserts the parameter types onto the array somewhere in the beginning i would guess since the value 0 is passed but hey it could be in the end too ;)
Build it as a string, but put your values into an array and pass that to bindd_param. (and substitute ?'s for values in your SQL string.
$stmt = $mysqli->prepare("UPDATE mytable SET myvar1=?, myvar2=... WHERE id = ?")) {
$stmt->bind_param("ss...", $_POST['myvar1'], $_POST['myvar2']...);
For example:
$args = array();
$sql = "UPDATE sometable SET ";
$sep = "";
$paramtypes = "";
foreach($_POST as $key => $val) {
$sql .= $sep.$key." = '?'";
$paramtypes .= "s"; // you'll need to map these based on name
array_push($args, $val);
$sep = ",";
}
$sql .= " WHERE id = ?";
array_push($args, $id);
array_insert($args, $paramtypes, 0);
$stmt = $mysqli->prepare($sql);
call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
$stmt->bind_param($args);

Categories