国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php框架 > ZendFramework > Zend Framework教程-Zend_Db-数据库操作1-Zend_Db_Adapter

Zend Framework教程-Zend_Db-数据库操作1-Zend_Db_Adapter

来源:程序员人生   发布时间:2014-06-13 07:05:35 阅读次数:4091次

上一节,大概了解了Zend Framework完成数据库操作的常用类,下面一一简单介绍其用法。


Zend_Db_Adapter是我们操作数据库的常用方式,以下是几个比较重要的功能使用说明:


1.建立数据库链接

		require_once 'Zend/Db.php';		$params = array ('host'     => '127.0.0.1',		                 'username' => 'root',		                 'password' => '',		                 'dbname'   => 'test');				$db = Zend_Db::factory('PDO_MYSQL', $params);

采用工厂模式建立数据库链接。

    public static function factory($adapter, $config = array())

第一个参数是采用何种方式链接。

第二个参数是指定传递的链接参数。

我们采用的是‘PDO_MYSQL’连接方式。具体参数规则如下:

/*         * Form full adapter class name         */        $adapterNamespace = 'Zend_Db_Adapter';        if (isset($config['adapterNamespace'])) {            if ($config['adapterNamespace'] != '') {                $adapterNamespace = $config['adapterNamespace'];            }            unset($config['adapterNamespace']);        }        // Adapter no longer normalized- see http://framework.zend.com/issues/browse/ZF-5606        $adapterName = $adapterNamespace . '_';        $adapterName .= str_replace(' ', '_', ucwords(str_replace('_', ' ', strtolower($adapter))));        /*         * Load the adapter class.  This throws an exception         * if the specified class cannot be loaded.         */        if (!class_exists($adapterName)) {            require_once 'Zend/Loader.php';            Zend_Loader::loadClass($adapterName);        }


以下是常见的方式,取Zend_Db_Adapter_后面的名字作为参数。


Zend_Db_Adapter_Pdo_Mysql

Zend_Db_Adapter_Pdo_Sqlite

Zend_Db_Adapter_Pdo_Pgsql

Zend_Db_Adapter_Pdo_Mssql


Zend_Db_Adapter_Mysqli

Zend_Db_Adapter_Db2

Zend_Db_Adapter_Oracle


Zend_Db_Adapter_Sqlsrv


具体的配置参数可以使用查看Zend_Db_Adapter_Abstract源码的$config。当然你可以把配置参数放到application.ini配置文件,这里不再累述。


具体的实现方法如下:

 /**     * Factory for Zend_Db_Adapter_Abstract classes.     *     * First argument may be a string containing the base of the adapter class     * name, e.g. 'Mysqli' corresponds to class Zend_Db_Adapter_Mysqli.  This     * name is currently case-insensitive, but is not ideal to rely on this behavior.     * If your class is named 'My_Company_Pdo_Mysql', where 'My_Company' is the namespace     * and 'Pdo_Mysql' is the adapter name, it is best to use the name exactly as it     * is defined in the class.  This will ensure proper use of the factory API.     *     * First argument may alternatively be an object of type Zend_Config.     * The adapter class base name is read from the 'adapter' property.     * The adapter config parameters are read from the 'params' property.     *     * Second argument is optional and may be an associative array of key-value     * pairs.  This is used as the argument to the adapter constructor.     *     * If the first argument is of type Zend_Config, it is assumed to contain     * all parameters, and the second argument is ignored.     *     * @param  mixed $adapter String name of base adapter class, or Zend_Config object.     * @param  mixed $config  OPTIONAL; an array or Zend_Config object with adapter parameters.     * @return Zend_Db_Adapter_Abstract     * @throws Zend_Db_Exception     */    public static function factory($adapter, $config = array())    {        if ($config instanceof Zend_Config) {            $config = $config->toArray();        }        /*         * Convert Zend_Config argument to plain string         * adapter name and separate config object.         */        if ($adapter instanceof Zend_Config) {            if (isset($adapter->params)) {                $config = $adapter->params->toArray();            }            if (isset($adapter->adapter)) {                $adapter = (string) $adapter->adapter;            } else {                $adapter = null;            }        }        /*         * Verify that adapter parameters are in an array.         */        if (!is_array($config)) {            /**             * @see Zend_Db_Exception             */            require_once 'Zend/Db/Exception.php';            throw new Zend_Db_Exception('Adapter parameters must be in an array or a Zend_Config object');        }        /*         * Verify that an adapter name has been specified.         */        if (!is_string($adapter) || empty($adapter)) {            /**             * @see Zend_Db_Exception             */            require_once 'Zend/Db/Exception.php';            throw new Zend_Db_Exception('Adapter name must be specified in a string');        }        /*         * Form full adapter class name         */        $adapterNamespace = 'Zend_Db_Adapter';        if (isset($config['adapterNamespace'])) {            if ($config['adapterNamespace'] != '') {                $adapterNamespace = $config['adapterNamespace'];            }            unset($config['adapterNamespace']);        }        // Adapter no longer normalized- see http://framework.zend.com/issues/browse/ZF-5606        $adapterName = $adapterNamespace . '_';        $adapterName .= str_replace(' ', '_', ucwords(str_replace('_', ' ', strtolower($adapter))));        /*         * Load the adapter class.  This throws an exception         * if the specified class cannot be loaded.         */        if (!class_exists($adapterName)) {            require_once 'Zend/Loader.php';            Zend_Loader::loadClass($adapterName);        }        /*         * Create an instance of the adapter class.         * Pass the config to the adapter class constructor.         */        $dbAdapter = new $adapterName($config);        /*         * Verify that the object created is a descendent of the abstract adapter type.         */        if (! $dbAdapter instanceof Zend_Db_Adapter_Abstract) {            /**             * @see Zend_Db_Exception             */            require_once 'Zend/Db/Exception.php';            throw new Zend_Db_Exception("Adapter class '$adapterName' does not extend Zend_Db_Adapter_Abstract");        }        return $dbAdapter;    }


2.常见的方法


主要在Zend_Db_Adapter_Abstract抽象父类和具体的实现类。

以pdo方式的mysql文件,说明常用的功能:

<?phpabstract class Zend_Db_Adapter_Abstract{    public function query($sql, $bind = array())     public function beginTransaction()     public function commit()     public function rollBack()     public function insert($table, array $bind)     public function update($table, array $bind, $where = '')     public function delete($table, $where = '')     public function select()     public function getFetchMode()     public function fetchAll($sql, $bind = array(), $fetchMode = null)     public function fetchRow($sql, $bind = array(), $fetchMode = null)     public function fetchAssoc($sql, $bind = array())     public function fetchCol($sql, $bind = array())     public function fetchPairs($sql, $bind = array())     public function fetchOne($sql, $bind = array())     public function quote($value, $type = null)     public function quoteInto($text, $value, $type = null, $count = null)     public function quoteIdentifier($ident, $auto=false)     public function quoteColumnAs($ident, $alias, $auto=false)     public function quoteTableAs($ident, $alias = null, $auto = false) }

<?phpabstract class Zend_Db_Adapter_Pdo_Abstract extends Zend_Db_Adapter_Abstract{     public function isConnected()     public function closeConnection()     public function prepare($sql)     public function lastInsertId($tableName = null, $primaryKey = null)     public function query($sql, $bind = array())     public function exec($sql)     public function setFetchMode($mode)     public function supportsParameters($type)     public function getServerVersion() }

<?phpclass Zend_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Abstract{       public function limit($sql, $count, $offset = 0)}


3.常见的方法的使用举例


1).添加引号防止数据库攻击

你应该处理将在sql语句中使用的条件值;这对于防止sql语句攻击是很有好处的。 Zend_Db_Adapter (通过pdo)提供了两种方法帮助你手动的为条件值加上引号。

第一种是quote() 方法. 该方法会根据数据库adapter为标量加上 合适的引号;假如你试图对一个数组做quote操作, 它将为数组中 每个元素加上引号,并用","分隔返回. (对于参数很多的函数来说,这点是很有帮助的).

<?php// 创建一个$db对象,假设数据库adapter为mysql.// 为标量加引号$value = $db->quote('St John"s Wort');// $value 现在变成了 '"St John"s Wort"' (注意两边的引号)// 为数组加引号$value = $db->quote(array('a', 'b', 'c');// $value 现在变成了 '"a", "b", "c"' (","分隔的字符串)?>

第二种是 quoteInto() 方法. 你提供一个包含问号占 位符的基础字符串 , 然后在该位置加入带引号的标量或者数组. 该 方法对于随需构建查询sql语句和条件语句是很有帮助的. 使用 quoteInto处理过的标量和数组返回结果与quote() 方法相同.

<?php// 创建一个$db对象,假设数据库adapter为mysql.// 在where语句中为标量加上引号$where = $db->quoteInto('id = ?', 1);// $where 现在为 'id = "1"' (注意两边的引号)// 在where语句中为数组加上引号$where = $db->quoteInto('id IN(?)', array(1, 2, 3));// $where 现在为 'id IN("1", "2", "3")' (一个逗号分隔的字符串)?>

2).直接查询

一旦你得到了一个Zend_Db_Adapter 实例, 你可以直接 执行sql语句进行查询.Zend_Db_Adapter 传送这些sql语 句到底层的PDO对象,由PDO对象组合并执行他们,在有查询结果的情况 下,返回一个PDOStatement对象以便对结果进行处理。

<?php// 创建一个$db对象,然后查询数据库// 使用完整的sql语句直接进行查询.$sql = $db->quoteInto(    'SELECT * FROM example WHERE date > ?',    '2006-01-01');$result = $db->query($sql);// 使用PDOStatement对象$result将所有结果数据放到一个数组中$rows = $result->fetchAll();?>


你可以将数据自动的绑定到你的查询中。这意味着你在查询中可以设定 多个指定的占位符,然后传送一个数组数据以代替这些占位符。这些替 换的数据是自动进行加引号处理的,为防止数据库攻击提供了更强的安 全性。

<?php// 创建一个$db对象,然后查询数据库.// 这一次,使用绑定的占位符.$result = $db->query(    'SELECT * FROM example WHERE date > :placeholder',    array('placeholder' => '2006-01-01'));// 使用PDOStatement对象$result将所有结果数据放到一个数组中$rows = $result->fetchAll();?>


或者,你也可以手工设置sql语句和绑定数据到sql语句。这一功能通过 prepare() 方法得到一个设定好的PDOStatement对象,以便直 接进行数据库操作.

<?php// 创建一个$db对象,然后查询数据库.// 这次, 设定一个 PDOStatement 对象进行手工绑定.$stmt = $db->prepare('SELECT * FROM example WHERE date > :placeholder');$stmt->bindValue('placeholder', '2006-01-01');$stmt->execute();// 使用PDOStatement对象$result将所有结果数据放到一个数组中$rows = $stmt->fetchAll();?>

3).事务处理

默认情况下,PDO(因此 Zend_Db_Adapter 也是)是采用自动commit模式。 也就是说,所有的数据库操作执行时就做了commit操作。假如你试图执行事务处理,最 简单的是调用 beginTransaction()方法,然后选择commit或者rollback。 之后,Zend_Db_Adapter会回到自动commit模式下,直到你再次调用beginTransaction()方法

<?php// 创建一个 $db对象, 然后开始做一个事务处理.$db->beginTransaction();// 尝试数据库操作.// 假如成功,commit该操作;// 假如, roll back.try {    $db->query(...);    $db->commit();} catch (Exception $e) {    $db->rollBack();    echo $e->getMessage();}?>


4).插入数据行

为了方便起见,你可以使用 insert()方法将要插入的数据绑定并创建 一个insert语句(绑定的数据是自动进行加引号处理以避免数据库攻击的)

返回值并 不是 最后插入的数据的id,这样做的原因在于一些表 并没有一个自增的字段;相反的,这个插入的返回值是改变的数据行数(通常情况为1)。 假如你需要最后插入的数据id,可以在insert执行后调用lastInsertId() 方法。

<?php//// INSERT INTO round_table//     (noble_title, first_name, favorite_color)//     VALUES ("King", "Arthur", "blue");//// 创建一个 $db对象, 然后...// 以"列名"=>"数据"的格式格式构造插入数组,插入数据行$row = array (    'noble_title'    => 'King',    'first_name'     => 'Arthur',    'favorite_color' => 'blue',);// 插入数据的数据表$table = 'round_table';// i插入数据行并返回行数$rows_affected = $db->insert($table, $row);$last_insert_id = $db->lastInsertId();?>


5).更新数据行

为了方便起见,你可以使用 update() 方法确定需要update的数据并且创建一个 update语句(确定的数据是自动加引号处理以避免数据库攻击的)。

你可以提供一个可选的where语句说明update的条件(注意:where语句并 不是一个绑定参数,所以你需要自己数据进行加引号的操作)。

<?php//// UPDATE round_table//     SET favorite_color = "yellow"//     WHERE first_name = "Robin";//// 创建一个 $db对象, 然后...// 以"列名"=>"数据"的格式构造更新数组,更新数据行$set = array (    'favorite_color' => 'yellow',);// 更新的数据表$table = 'round_table';// where语句$where = $db->quoteInto('first_name = ?', 'Robin');// 更新表数据,返回更新的行数$rows_affected = $db->update($table, $set, $where);?>


6).删除数据行

为了方便起见,你可以使用 delete() 方法创建一个delete语句;你 也可以提供一个where语句以说明数据的删除条件。(注意:where语句并不是一个绑 定参数,所以你需要自己进行数据加引号处理)。

<?php//// 需要删除数据的表//     WHERE first_name = "Patsy";//// 创建一个 $db对象, 然后...// 设定需要删除数据的表$table = 'round_table';// where条件语句$where = $db->quoteInto('first_name = ?', 'Patsy');// 删除数据并得到影响的行数$rows_affected = $db->delete($table, $where);?>


7).取回查询结果

尽管你可以使用query()方法直接对数据库进行操作,但是通常情况 下,仍然还是需要选择数据行并返回结果。以fetch开头的一系列的 方法可以实现这个要求。对于每一种fetch系列 的方法来说,你需 要传送一个select的sql语句;假如你在操作语句中使用指定的占位符,你也可以 传送一个绑定数据的数组对你的操作语句进行处理和替换。Fetch系列 的方法包括:

  • fetchAll()

  • fetchAssoc()

  • fetchCol()

  • fetchOne()

  • fetchPairs()

  • fetchRow()

    <?php// 创建一个 $db对象, 然后...// 取回结果集中所有字段的值,作为连续数组返回$result = $db->fetchAll(    "SELECT * FROM round_table WHERE noble_title = :title",    array('title' => 'Sir'));// 取回结果集中所有字段的值,作为关联数组返回// 第一个字段作为码$result = $db->fetchAssoc(    "SELECT * FROM round_table WHERE noble_title = :title",    array('title' => 'Sir'));// 取回所有结果行的第一个字段名$result = $db->fetchCol(    "SELECT first_name FROM round_table WHERE noble_title = :title",    array('title' => 'Sir'));// 只取回第一个字段值$result = $db->fetchOne(    "SELECT COUNT(*) FROM round_table WHERE noble_title = :title",    array('title' => 'Sir'));// 取回一个相关数组,第一个字段值为码// 第二个字段为值$result = $db->fetchPairs(    "SELECT first_name, favorite_color FROM round_table WHERE noble_title = :title",    array('title' => 'Sir'));// 只取回结果集的第一行$result = $db->fetchRow(    "SELECT * FROM round_table WHERE first_name = :name",    array('name' => 'Lancelot'));?>




生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生