开发者

Return an array from mysqli stmt query

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 error开发者_StackOverflow社区s 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()


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.


 $servername = "localhost"; $username = "root"; $password = ""; $dbnam = "test";

 // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection if (mysqli_connect_errno()) {
 die("Connection failed: %s\n" . mysqli_connect_errno()); }

$stmt = mysqli_prepare($conn, "SELECT * FROM myguests") or
die(mysqli_error($conn));   mysqli_stmt_execute($stmt);

$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);
 while(mysqli_stmt_fetch($stmt))    print_r($out);

$stmt->close(); $conn->close();

Works great on me, hope it helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜