试图理解zend中的函数查询

时间:2013-04-19 07:39:37

标签: php zend-framework

/**
     * Prepares and executes an SQL statement with bound data.
     *
     * @param  mixed  $sql  The SQL statement with placeholders.
     *                      May be a string or Zend_Db_Select.
     * @param  mixed  $bind An array of data to bind to the placeholders.
     * @return Zend_Db_Statement_Interface
     */ 
    public function query($sql, $bind = array())
        {
            // connect to the database if needed
            $this->_connect();

            // is the $sql a Zend_Db_Select object?
            if ($sql instanceof Zend_Db_Select) {
                if (empty($bind)) {
                    $bind = $sql->getBind();
                }

                $sql = $sql->assemble();
            }

            // make sure $bind to an array;
            // don't use (array) typecasting because
            // because $bind may be a Zend_Db_Expr object
            if (!is_array($bind)) {
                $bind = array($bind);
            }

            // prepare and execute the statement with profiling
            $stmt = $this->prepare($sql);
            $stmt->execute($bind);

            // return the results embedded in the prepared statement object
            $stmt->setFetchMode($this->_fetchMode);
            return $stmt;
        }

以上代码来自Zend/Db/Adapter/Abstract.php,虽然有评论,但我仍然不理解$ bind的用法。如果可能,请举例说明 感谢。

1 个答案:

答案 0 :(得分:0)

$bind是参数化查询的数组参数:

// $bind with single param:
$obj->query('SELECT * FROM TableName WHERE IDColumn = ?', array(1));
// OR
$obj->query('SELECT * FROM TableName WHERE IDColumn = ?', 1);

意思是:

SELECT * FROM TableName WHERE IDColumn = 1

// $bind with multiparams:
$obj->query('SELECT * FROM TableName WHERE somefield BETWEEN ? AND ?', array(10, 15));

意思是:

SELECT * FROM TableName WHERE somefield BETWEEN 10 AND 15

// $bind omitted at all:
$obj->query('SELECT * FROM TableName ORDER BY somefield');

意思是:

SELECT * FROM TableName ORDER BY somefield

如果$sqlZend_Db_Select的实例,那么它可能有一些自己的绑定。因此,如果提供的$bind为空/省略,则为其分配$sql的绑定。