Prepared statements with an array [duplicate]
I have a function to do a simple insert, but am trying to make the method more robust by passing an array. And this is the array I pass into it:
$form_data = array(
"sort_order"=>$_POST['sort_order'],
"name"=>$_POST['page_name'],
"text"=>$_POST['page_text'],
开发者_如何学编程 "image"=>$_POST['page_image'],
"meta_desc"=>$_POST['meta_desc'],
"meta_kw"=>$_POST['meta_kw'],
"meta_author"=>$_POST['meta_author'],
"image_thumb"=>"NULL",
);
Here is the function code:
public function insert_data($array){
$keys = array();
$values = array();
foreach($array as $k => $v){
$keys[] = $k;
if(!empty($v)){
$values[] = $v;
} else {
$values[] = "NULL";
}
}
$stmt = self::$mysqli->stmt_init();
$query = "INSERT INTO `".DB_TABLE_PAGES."` (".implode(",",$keys).") VALUES (?,?,?,?,?,?,?,?)";
$stmt->prepare($query);
$stmt->bind_param('ssssssss',implode(",",$values));
//$stmt->execute();
}
But I get this error:
Number of elements in type definition string doesn't match number of bind variables.
I know what the problem is, but I don't understand how I can achieve it.
Try this:
public function insert_data($array){
$placeholders = array_fill(0, count($array), '?');
$keys = $values = array();
foreach($array as $k => $v) {
$keys[] = $k;
$values[] = !empty($v) ? $v : null;
}
$stmt = self::$mysqli->stmt_init();
$query = 'INSERT INTO `'.DB_TABLE_PAGES.'` '.
'('.implode(',', $keys).') VALUES '.
'('.implode(',', $placeholders).')';
$stmt->prepare($query);
call_user_func_array(
array($stmt, 'bind_param'),
array_merge(
array(str_repeat('s', count($values))),
$values
)
);
$stmt->execute();
}
Or better yet, use PDO instead:
public function insert_data($array){
$placeholders = array_fill(0, count($array), '?');
$keys = $values = array();
foreach($array as $k => $v){
$keys[] = $k;
$values[] = !empty($v) ? $v : null;
}
// assuming the PDO instance is $pdo
$query = 'INSERT INTO `'.DB_TABLE_PAGES.'` '.
'('.implode(',', $keys).') VALUES '.
'('.implode(',', $placeholders).')';
$stmt = $pdo->prepare($query);
$stmt->execute($values);
}
Note: I've used the null
constant because the "NULL"
string will be escaped as a string (not as a null value).
I found something a little more concise.
Disclaimer, this works only since PHP 5.6 using the unpacking (splat) operator:
public function genericQueryWithParams($query, $params, $types)
{
$sql = $this->db->prepare($query));
$sql->bind_param($types, ...$params);
$sql->execute();
return $sql->get_result();
}
Instead of bind_param (which in my mind is confusing at all times), just do:
$stmt->execute($values);
You can also get rid of your loop by using array_keys() and array_values()
精彩评论