I recently started using MySQLi prepared statements. I did not liked how many rows of code that was needed for just a simple select statement. So I created a wrapper function, see the code below the questions below. Note: get_results() or PDO is not an option for me.
My questions are:
Will it slow down the performance noticeably?
Will it be more memory intensive because of the use of the result array?
- Will the $stmt->close() before the return cause any problems? For example maybe the result array data is also are freed from memory?
- Do I need to close or free anything else (except from closing the db connection)?
- Do you see any other problems with the function or could it be improved?
Code:
class DatabaseHelper{
static function select($con, $query, $formats, $params){
$a_params = array();
$param_type = '';
$n = count($formats);
for($i = 0; $i < $n; $i++) {
$param_type .= $formats[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_params[] = & $params[$i];
}
$stmt = $con->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $a_params);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$columns[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $columns);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
return $results;
}
}
Used like this for example:
$users = DatabaseHelper::select($conn, "SELECT name,username FROM users WHERE id > ?", "i", array(30));
foreach ($users as $row){
echo $row['username'] . " ". $row['name'] . "<br />";
}