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:
$for
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).
Though this is an old question it has popped up on several of my searches to find an eloquent answer to the same problem. After much searching, and an implementation of the solution provided by @netcoder I found something a little more concise.
Disclaimer, this is for php 5.6 using the unpacking (splat) operator:
public function genericQueryWithParams($query, $params, $types)
{
$db = new mysqli('localhost','username','password','schema');
if($sql = $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()