Mysqli get_result 替代方案 [英] Mysqli get_result alternative

查看:21
本文介绍了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'];
}

这在本地主机上运行良好,但我的网络托管服务器没有可用的 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?

推荐答案

这里有一个更简洁的解决方案,基于与 lx 答案:

Here is a neater solution based on the same principle as lx answer:

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天全站免登陆