I wasn't able to fully test the following since the server I am currently working on is missing the PHP module that allows me to call get_result on mysqli_stmt but maybe this could be helpful for someone:
<?php
class CustomMysqli extends \mysqli
{
public function queryPrepared($query, array $args)
{
$stmt = $this->prepare($query);
$params = [];
$types = array_reduce($args, function ($string, &$arg) use (&$params) {
$params[] = &$arg;
if (is_float($arg)) $string .= 'd';
elseif (is_integer($arg)) $string .= 'i';
elseif (is_string($arg)) $string .= 's';
else $string .= 'b';
return $string;
}, '');
array_unshift($params, $types);
call_user_func_array([$stmt, 'bind_param'], $params);
$result = $stmt->execute() ? $stmt->get_result() : false;
$stmt->close();
return $result;
}
}
$db = new CustomMysqli('host', 'user', 'password', 'database', 3306);
$result = $db->queryPrepared(
'SELECT * FROM table WHERE something = ? AND someotherthing = ? AND elsewhat = ?',
[
'dunno',
1,
'dontcare'
]
);
if (isset($result) && $result instanceof \mysqli_result) {
while (null !== ($row = $result->fetch_assoc())) {
echo '<pre>'.var_debug($row, true).'</pre>';
}
}
?>
NOTE: If you want to use this with a PHP version below 5.4 you have to use the old ugly array() syntax for arrays instead of the short [] syntax.