I’m trying to convert a site to use prepared mysql statements, however I’m having some trouble replacing my use of fetch_array()
.
The comments on php.net offer a solution which I would have thought should work but for some reason I’m getting strange undefined constant errors when calling a function via call_user_func_array()
can someone suggest a better way of doing it?
Here’s the function I’m using at the moment. I’ve dumbed it down a bit for posting on here (it’s part of a larger class which extends mysqli and handles error catching etc) so sorry if I’ve made any mistakes copy and pasting it.
public static function stmt_bind_assoc(&$stmt, &$out) { $data = mysqli_stmt_result_metadata($stmt); $fields = array(); $out = array(); $fields[0] = $stmt; $count = 1; while($field = mysqli_fetch_field($data)) { $fields[$count] = &$out[$field->name]; $count++; } call_user_func_array(mysqli_stmt_bind_result, $fields); }
public function fetch_array($rawQuery) { $stmt = $this->prepare($rawQuery); $row = array(); self::stmt_bind_assoc($stmt, $row); $result = $stmt->fetch(); $stmt->free(); return $result; }
The errors I get are:
Notice: Use of undefined constant mysqli_stmt_bind_result – assumed ‘mysqli_stmt_bind_result’
Fatal error: Call to undefined method mysqli_stmt::free()
Advertisement
Answer
The first error comes from your call_user_func_array
statement: you need quotes around the mysqli_stmt_bind_result
, otherwise PHP assumes it’s a constant.
And there’s no free()
function in mysqli_stmt
, use $stmt->free_result()
instead.