如何在PHP中抽象mysqli准备好的语句? [英] How can I abstract mysqli prepared statements in PHP?

查看:65
本文介绍了如何在PHP中抽象mysqli准备好的语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用自己的类进行数据库查询,扩展了mysqli:

I'm using my own class for database queries, extending mysqli:

class iDatabase extends mysqli
{
    public  $errorMsg;
    private $totalQueries;
    private $stmt;

    public function __construct()
    {
        parent::__construct( 'localhost', 'asd', 'asd', 'asd' );

        if ( mysqli_connect_errno() )
        {
            $this->errorMsg = 'Could not connect to server.<br /><i>' . mysqli_connect_error() . '</i>.';
            return;
        }

        parent::query( 'SET NAMES utf8' );
    }

}

但是,在执行查询并返回结果时遇到麻烦.我正在使用准备好的语句,但是值和结果的绑定方式使我感到困惑.经过一番研究,我想到了该函数,该函数可以接受查询和参数:

However I'm running into trouble when executing queries and getting back results. I'm using prepared statements, but the way values and results are bound is confusing me. After a bit of research I came up with this function that accepts the query and parameters:

public function psQuery( $query, $params )
{
    $this->stmt = parent::prepare( $query );
    call_user_func_array( array($this->stmt,'bind_param'), $params );
    $this->stmt->execute();
}

我的问题是,从中获得结果的最佳方法是什么?我需要使用bind_result,然后获取每一行,然后关闭该语句.我宁愿只为每行获取一个关联数组-可以吗?

My question is, what is the best way to get results back from this? I need to use bind_result, then fetch each row, then close the statement. I'd prefer to just get an associative array for each row - is that possible?

推荐答案

我在Zend_Db_Adapter_MysqliZend_Db_Statement_Mysqli类上做了很多工作,以使它起作用,因为我们想使它符合PDOPDOStatement界面.这非常费力,因为MySQLi坚持使您绑定变量以获得结果的方式混乱,并且PDOStatement支持多种获取模式.

I worked on the Zend_Db_Adapter_Mysqli and Zend_Db_Statement_Mysqli classes quite a bit to get this to work, since we wanted to make it conform to the PDO and PDOStatement interface. It was pretty laborious, because of the confusing way MySQLi insists on making you bind variables to get results, and the variety of fetch modes supported by PDOStatement.

如果要查看Zend_Db中的代码,请特别注意功能 Zend_Db_Statement_Mysqli::_execute()fetch().基本上,_execute()方法使用call_user_func_array()绑定变量引用数组.棘手的部分是您必须初始化数组,以便bind_result()函数获取引用.嗯,这还不是很清楚,所以请看一下代码.

If you want to see the code in Zend_Db, pay special attention to the functions Zend_Db_Statement_Mysqli::_execute() and fetch(). Basically, the _execute() method binds an array of variable references using call_user_func_array(). The tricky part is that you have to initialize the array so the bind_result() function gets the references. Uh, that wasn't totally clear, so go take a look at the code.

否则,只需使用PDO的MySQL驱动程序即可.那就是我要穿的鞋子.

Or else just use PDO's MySQL driver. That's what I would do in your shoes.

这篇关于如何在PHP中抽象mysqli准备好的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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