Mysqli get_result替代 [英] Mysqli get_result alternative

查看:56
本文介绍了Mysqli get_result替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使用mysqli将所有SQL查询更改为准备好的语句.为了加快此过程,我创建了一个函数(performQuery)来代替mysql_query.它需要查询,绑定(例如"sdss")和要传入的变量,然后执行所有perpared语句.这意味着更改我所有的旧代码很容易.我的函数使用mysqli get_result()返回mysqli_result对象.

I've just changed all my sql queries to prepared statements using mysqli. To speed this process up I created a function (called performQuery) which replaces mysql_query. It takes the query, the bindings (like "sdss") and the variables to pass in, this then does all the perpared statement stuff. This meant changing all my old code was easy. My function returns a mysqli_result object using mysqli get_result().

这意味着我可以从以下位置更改旧代码:

This meant I could change my old code from:

$query = "SELECT x FROM y WHERE z = $var";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
    echo $row['x'];
}

$query = "SELECT x FROM y WHERE z = ?";
$result = performQuery($query,"s",$var);
while ($row = mysql_fetch_assoc($result)){
    echo $row['x'];
}

这在localhost上可以正常工作,但是我的网络托管服务器没有mysqlnd可用,因此get_result()不起作用.无法安装mysqlnd.

This works fine on localhost, but my web hosting server does not have mysqlnd available, therefore get_result() does not work. Installing mysqlnd is not an option.

从这里出发的最佳方法是什么?我可以创建一个替换get_result()的函数吗?

What is the best way to go from here? Can I create a function which replaces get_result(), and how?

推荐答案

以下是基于相同原理的更整洁的解决方案:

Here is a neater solution based on the same principle:

function get_result( $Statement ) {
    $RESULT = array();
    $Statement->store_result();
    for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
        $Metadata = $Statement->result_metadata();
        $PARAMS = array();
        while ( $Field = $Metadata->fetch_field() ) {
            $PARAMS[] = &$RESULT[ $i ][ $Field->name ];
        }
        call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
        $Statement->fetch();
    }
    return $RESULT;
}

使用mysqlnd ,您通常会这样做:

$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$Result = $Statement->get_result();
while ( $DATA = $Result->fetch_array() ) {
    // Do stuff with the data
}

没有mysqlnd :

$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$RESULT = get_result( $Statement );
while ( $DATA = array_shift( $RESULT ) ) {
    // Do stuff with the data
}

因此用法和语法几乎相同.主要区别在于替换函数返回结果数组,而不是结果对象.

So the usage and syntax are almost identical. The main difference is that the replacement function returns a result array, rather than a result object.

这篇关于Mysqli get_result替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆