欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Zend Framework入门教程之Zend_Db数据库操作详解

程序员文章站 2024-04-01 20:48:34
本文实例讲述了zend framework中zend_db数据库操作方法。分享给大家供大家参考,具体如下: 引言:zend操作数据库通过zend_db_adapter...

本文实例讲述了zend framework中zend_db数据库操作方法。分享给大家供大家参考,具体如下:

引言:zend操作数据库通过zend_db_adapter

它可以连接多种数据库,可以是db2数据库、mysqli数据库、oracle数据库。等等。

只需要配置相应的参数就可以了。

下面通过案例来展示一下其连接数据库的过程。

连接mysql数据库

代码:

<?php
require_once 'zend/db.php';
$params = array('host'=>'127.0.0.1',
  'username'=>'root',
  'password'=>'',
  'dbname'=>'test'
  );
$db = zend_db::factory('pdo_mysql',$params);

点评:

这是连接mysql的代码案例,提供相应的参数就可以了。连接不同的数据库,提供不同的参数。下面是sqlite的例子

代码:

<?php
require_once 'zend/db.php';
$params = array('dbname'=>'test.mdb');
$db = zend_db::factory('pdo_sqlite',$params);

点评:

sqlite明显参数不一样了,只需要提供数据库名字就可以了。
连接完数据库之后,就可以查询数据库信息以及操作数据库信息了。
如果查询呢?

下面是查询的代码案例:

<?php
require_once 'zend/db.php';
$params = array('host'=>'127.0.0.1',
  'username'=>'root',
  'password'=>'',
  'dbname'=>'test'
  );
$db = zend_db::factory('pdo_mysql',$params);
$sql = $db->quoteinto('select * from user where id<?','5');
$result = $db->query($sql);  //执行sql查询
$r_a = $result->fetchall(); //返回结果数组
print_r($r_a);

点评:

执行完上述代码,就会展示出数据库中前五条记录的信息。

那么这其中的玄机是什么呢?

我们来看一下源码。

我们来看看db.php中的factory方法

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))));
    print_r($adaptername);exit;
    /*
     * 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;
}

点评:这个方法就是核心了,代码量不多,但是作用很明确,它会通过你提供的两个参数,自动生成相应的数据库连接类的对象。具有一定的灵活性,机动性。

主要是其中的

$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目录下pdo目录下的mysql.php类。

不同的数据库,会引入不同的数据库文件。

我们来看看mysql.php类中的内容:

<?php
/**
 * zend framework
 *
 * license
 *
 * this source file is subject to the new bsd license that is bundled
 * with this package in the file license.txt.
 * it is also available through the world-wide-web at this url:
 * http://framework.zend.com/license/new-bsd
 * if you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  zend
 * @package  zend_db
 * @subpackage adapter
 * @copyright copyright (c) 2005-2012 zend technologies usa inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   new bsd license
 * @version  $id: mysql.php 24593 2012-01-05 20:35:02z matthew $
 */
/**
 * @see zend_db_adapter_pdo_abstract
 */
require_once 'zend/db/adapter/pdo/abstract.php';
/**
 * class for connecting to mysql databases and performing common operations.
 *
 * @category  zend
 * @package  zend_db
 * @subpackage adapter
 * @copyright copyright (c) 2005-2012 zend technologies usa inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   new bsd license
 */
class zend_db_adapter_pdo_mysql extends zend_db_adapter_pdo_abstract
{
  /**
   * pdo type.
   *
   * @var string
   */
  protected $_pdotype = 'mysql';
  /**
   * keys are uppercase sql datatypes or the constants
   * zend_db::int_type, zend_db::bigint_type, or zend_db::float_type.
   *
   * values are:
   * 0 = 32-bit integer
   * 1 = 64-bit integer
   * 2 = float or decimal
   *
   * @var array associative array of datatypes to values 0, 1, or 2.
   */
  protected $_numericdatatypes = array(
    zend_db::int_type  => zend_db::int_type,
    zend_db::bigint_type => zend_db::bigint_type,
    zend_db::float_type => zend_db::float_type,
    'int'        => zend_db::int_type,
    'integer'      => zend_db::int_type,
    'mediumint'     => zend_db::int_type,
    'smallint'      => zend_db::int_type,
    'tinyint'      => zend_db::int_type,
    'bigint'       => zend_db::bigint_type,
    'serial'       => zend_db::bigint_type,
    'dec'        => zend_db::float_type,
    'decimal'      => zend_db::float_type,
    'double'       => zend_db::float_type,
    'double precision'  => zend_db::float_type,
    'fixed'       => zend_db::float_type,
    'float'       => zend_db::float_type
  );
  /**
   * override _dsn() and ensure that charset is incorporated in mysql
   * @see zend_db_adapter_pdo_abstract::_dsn()
   */
  protected function _dsn()
  {
    $dsn = parent::_dsn();
    if (isset($this->_config['charset'])) {
      $dsn .= ';charset=' . $this->_config['charset'];
    }
    return $dsn;
  }
  /**
   * creates a pdo object and connects to the database.
   *
   * @return void
   * @throws zend_db_adapter_exception
   */
  protected function _connect()
  {
    if ($this->_connection) {
      return;
    }
    if (!empty($this->_config['charset'])) {
      $initcommand = "set names '" . $this->_config['charset'] . "'";
      $this->_config['driver_options'][1002] = $initcommand; // 1002 = pdo::mysql_attr_init_command
    }
    parent::_connect();
  }
  /**
   * @return string
   */
  public function getquoteidentifiersymbol()
  {
    return "`";
  }
  /**
   * returns a list of the tables in the database.
   *
   * @return array
   */
  public function listtables()
  {
    return $this->fetchcol('show tables');
  }
  /**
   * returns the column descriptions for a table.
   *
   * the return value is an associative array keyed by the column name,
   * as returned by the rdbms.
   *
   * the value of each array element is an associative array
   * with the following keys:
   *
   * schema_name   => string; name of database or schema
   * table_name    => string;
   * column_name   => string; column name
   * column_position => number; ordinal position of column in table
   * data_type    => string; sql datatype name of column
   * default     => string; default expression of column, null if none
   * nullable     => boolean; true if column can have nulls
   * length      => number; length of char/varchar
   * scale      => number; scale of numeric/decimal
   * precision    => number; precision of numeric/decimal
   * unsigned     => boolean; unsigned property of an integer type
   * primary     => boolean; true if column is part of the primary key
   * primary_position => integer; position of column in primary key
   * identity     => integer; true if column is auto-generated with unique values
   *
   * @param string $tablename
   * @param string $schemaname optional
   * @return array
   */
  public function describetable($tablename, $schemaname = null)
  {
    // @todo use information_schema someday when mysql's
    // implementation has reasonably good performance and
    // the version with this improvement is in wide use.
    if ($schemaname) {
      $sql = 'describe ' . $this->quoteidentifier("$schemaname.$tablename", true);
    } else {
      $sql = 'describe ' . $this->quoteidentifier($tablename, true);
    }
    $stmt = $this->query($sql);
    // use fetch_num so we are not dependent on the case attribute of the pdo connection
    $result = $stmt->fetchall(zend_db::fetch_num);
    $field  = 0;
    $type  = 1;
    $null  = 2;
    $key   = 3;
    $default = 4;
    $extra  = 5;
    $desc = array();
    $i = 1;
    $p = 1;
    foreach ($result as $row) {
      list($length, $scale, $precision, $unsigned, $primary, $primaryposition, $identity)
        = array(null, null, null, null, false, null, false);
      if (preg_match('/unsigned/', $row[$type])) {
        $unsigned = true;
      }
      if (preg_match('/^((?:var)?char)\((\d+)\)/', $row[$type], $matches)) {
        $row[$type] = $matches[1];
        $length = $matches[2];
      } else if (preg_match('/^decimal\((\d+),(\d+)\)/', $row[$type], $matches)) {
        $row[$type] = 'decimal';
        $precision = $matches[1];
        $scale = $matches[2];
      } else if (preg_match('/^float\((\d+),(\d+)\)/', $row[$type], $matches)) {
        $row[$type] = 'float';
        $precision = $matches[1];
        $scale = $matches[2];
      } else if (preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/', $row[$type], $matches)) {
        $row[$type] = $matches[1];
        // the optional argument of a mysql int type is not precision
        // or length; it is only a hint for display width.
      }
      if (strtoupper($row[$key]) == 'pri') {
        $primary = true;
        $primaryposition = $p;
        if ($row[$extra] == 'auto_increment') {
          $identity = true;
        } else {
          $identity = false;
        }
        ++$p;
      }
      $desc[$this->foldcase($row[$field])] = array(
        'schema_name'   => null, // @todo
        'table_name'    => $this->foldcase($tablename),
        'column_name'   => $this->foldcase($row[$field]),
        'column_position' => $i,
        'data_type'    => $row[$type],
        'default'     => $row[$default],
        'nullable'     => (bool) ($row[$null] == 'yes'),
        'length'      => $length,
        'scale'      => $scale,
        'precision'    => $precision,
        'unsigned'     => $unsigned,
        'primary'     => $primary,
        'primary_position' => $primaryposition,
        'identity'     => $identity
      );
      ++$i;
    }
    return $desc;
  }
  /**
   * adds an adapter-specific limit clause to the select statement.
   *
   * @param string $sql
   * @param integer $count
   * @param integer $offset optional
   * @throws zend_db_adapter_exception
   * @return string
   */
   public function limit($sql, $count, $offset = 0)
   {
    $count = intval($count);
    if ($count <= 0) {
      /** @see zend_db_adapter_exception */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception("limit argument count=$count is not valid");
    }
    $offset = intval($offset);
    if ($offset < 0) {
      /** @see zend_db_adapter_exception */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception("limit argument offset=$offset is not valid");
    }
    $sql .= " limit $count";
    if ($offset > 0) {
      $sql .= " offset $offset";
    }
    return $sql;
  }
}

这里又引入了一个abstract类,抽象类

<?php
/**
 * zend framework
 *
 * license
 *
 * this source file is subject to the new bsd license that is bundled
 * with this package in the file license.txt.
 * it is also available through the world-wide-web at this url:
 * http://framework.zend.com/license/new-bsd
 * if you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  zend
 * @package  zend_db
 * @subpackage adapter
 * @copyright copyright (c) 2005-2012 zend technologies usa inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   new bsd license
 * @version  $id: abstract.php 24593 2012-01-05 20:35:02z matthew $
 */
/**
 * @see zend_db_adapter_abstract
 */
require_once 'zend/db/adapter/abstract.php';
/**
 * @see zend_db_statement_pdo
 */
require_once 'zend/db/statement/pdo.php';
/**
 * class for connecting to sql databases and performing common operations using pdo.
 *
 * @category  zend
 * @package  zend_db
 * @subpackage adapter
 * @copyright copyright (c) 2005-2012 zend technologies usa inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   new bsd license
 */
abstract class zend_db_adapter_pdo_abstract extends zend_db_adapter_abstract
{
  /**
   * default class name for a db statement.
   *
   * @var string
   */
  protected $_defaultstmtclass = 'zend_db_statement_pdo';
  /**
   * creates a pdo dsn for the adapter from $this->_config settings.
   *
   * @return string
   */
  protected function _dsn()
  {
    // baseline of dsn parts
    $dsn = $this->_config;
    // don't pass the username, password, charset, persistent and driver_options in the dsn
    unset($dsn['username']);
    unset($dsn['password']);
    unset($dsn['options']);
    unset($dsn['charset']);
    unset($dsn['persistent']);
    unset($dsn['driver_options']);
    // use all remaining parts in the dsn
    foreach ($dsn as $key => $val) {
      $dsn[$key] = "$key=$val";
    }
    return $this->_pdotype . ':' . implode(';', $dsn);
  }
  /**
   * creates a pdo object and connects to the database.
   *
   * @return void
   * @throws zend_db_adapter_exception
   */
  protected function _connect()
  {
    // if we already have a pdo object, no need to re-connect.
    if ($this->_connection) {
      return;
    }
    // get the dsn first, because some adapters alter the $_pdotype
    $dsn = $this->_dsn();
    // check for pdo extension
    if (!extension_loaded('pdo')) {
      /**
       * @see zend_db_adapter_exception
       */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception('the pdo extension is required for this adapter but the extension is not loaded');
    }
    // check the pdo driver is available
    if (!in_array($this->_pdotype, pdo::getavailabledrivers())) {
      /**
       * @see zend_db_adapter_exception
       */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception('the ' . $this->_pdotype . ' driver is not currently installed');
    }
    // create pdo connection
    $q = $this->_profiler->querystart('connect', zend_db_profiler::connect);
    // add the persistence flag if we find it in our config array
    if (isset($this->_config['persistent']) && ($this->_config['persistent'] == true)) {
      $this->_config['driver_options'][pdo::attr_persistent] = true;
    }
    try {
      $this->_connection = new pdo(
        $dsn,
        $this->_config['username'],
        $this->_config['password'],
        $this->_config['driver_options']
      );
      $this->_profiler->queryend($q);
      // set the pdo connection to perform case-folding on array keys, or not
      $this->_connection->setattribute(pdo::attr_case, $this->_casefolding);
      // always use exceptions.
      $this->_connection->setattribute(pdo::attr_errmode, pdo::errmode_exception);
    } catch (pdoexception $e) {
      /**
       * @see zend_db_adapter_exception
       */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception($e->getmessage(), $e->getcode(), $e);
    }
  }
  /**
   * test if a connection is active
   *
   * @return boolean
   */
  public function isconnected()
  {
    return ((bool) ($this->_connection instanceof pdo));
  }
  /**
   * force the connection to close.
   *
   * @return void
   */
  public function closeconnection()
  {
    $this->_connection = null;
  }
  /**
   * prepares an sql statement.
   *
   * @param string $sql the sql statement with placeholders.
   * @param array $bind an array of data to bind to the placeholders.
   * @return pdostatement
   */
  public function prepare($sql)
  {
    $this->_connect();
    $stmtclass = $this->_defaultstmtclass;
    if (!class_exists($stmtclass)) {
      require_once 'zend/loader.php';
      zend_loader::loadclass($stmtclass);
    }
    $stmt = new $stmtclass($this, $sql);
    $stmt->setfetchmode($this->_fetchmode);
    return $stmt;
  }
  /**
   * gets the last id generated automatically by an identity/autoincrement column.
   *
   * as a convention, on rdbms brands that support sequences
   * (e.g. oracle, postgresql, db2), this method forms the name of a sequence
   * from the arguments and returns the last id generated by that sequence.
   * on rdbms brands that support identity/autoincrement columns, this method
   * returns the last value generated for such a column, and the table name
   * argument is disregarded.
   *
   * on rdbms brands that don't support sequences, $tablename and $primarykey
   * are ignored.
   *
   * @param string $tablename  optional name of table.
   * @param string $primarykey optional name of primary key column.
   * @return string
   */
  public function lastinsertid($tablename = null, $primarykey = null)
  {
    $this->_connect();
    return $this->_connection->lastinsertid();
  }
  /**
   * special handling for pdo query().
   * all bind parameter names must begin with ':'
   *
   * @param string|zend_db_select $sql the sql statement with placeholders.
   * @param array $bind an array of data to bind to the placeholders.
   * @return zend_db_statement_pdo
   * @throws zend_db_adapter_exception to re-throw pdoexception.
   */
  public function query($sql, $bind = array())
  {
    if (empty($bind) && $sql instanceof zend_db_select) {
      $bind = $sql->getbind();
    }
    if (is_array($bind)) {
      foreach ($bind as $name => $value) {
        if (!is_int($name) && !preg_match('/^:/', $name)) {
          $newname = ":$name";
          unset($bind[$name]);
          $bind[$newname] = $value;
        }
      }
    }
    try {
      return parent::query($sql, $bind);
    } catch (pdoexception $e) {
      /**
       * @see zend_db_statement_exception
       */
      require_once 'zend/db/statement/exception.php';
      throw new zend_db_statement_exception($e->getmessage(), $e->getcode(), $e);
    }
  }
  /**
   * executes an sql statement and return the number of affected rows
   *
   * @param mixed $sql the sql statement with placeholders.
   *           may be a string or zend_db_select.
   * @return integer   number of rows that were modified
   *           or deleted by the sql statement
   */
  public function exec($sql)
  {
    if ($sql instanceof zend_db_select) {
      $sql = $sql->assemble();
    }
    try {
      $affected = $this->getconnection()->exec($sql);
      if ($affected === false) {
        $errorinfo = $this->getconnection()->errorinfo();
        /**
         * @see zend_db_adapter_exception
         */
        require_once 'zend/db/adapter/exception.php';
        throw new zend_db_adapter_exception($errorinfo[2]);
      }
      return $affected;
    } catch (pdoexception $e) {
      /**
       * @see zend_db_adapter_exception
       */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception($e->getmessage(), $e->getcode(), $e);
    }
  }
  /**
   * quote a raw string.
   *
   * @param string $value   raw string
   * @return string      quoted string
   */
  protected function _quote($value)
  {
    if (is_int($value) || is_float($value)) {
      return $value;
    }
    $this->_connect();
    return $this->_connection->quote($value);
  }
  /**
   * begin a transaction.
   */
  protected function _begintransaction()
  {
    $this->_connect();
    $this->_connection->begintransaction();
  }
  /**
   * commit a transaction.
   */
  protected function _commit()
  {
    $this->_connect();
    $this->_connection->commit();
  }
  /**
   * roll-back a transaction.
   */
  protected function _rollback() {
    $this->_connect();
    $this->_connection->rollback();
  }
  /**
   * set the pdo fetch mode.
   *
   * @todo support fetch_class and fetch_into.
   *
   * @param int $mode a pdo fetch mode.
   * @return void
   * @throws zend_db_adapter_exception
   */
  public function setfetchmode($mode)
  {
    //check for pdo extension
    if (!extension_loaded('pdo')) {
      /**
       * @see zend_db_adapter_exception
       */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception('the pdo extension is required for this adapter but the extension is not loaded');
    }
    switch ($mode) {
      case pdo::fetch_lazy:
      case pdo::fetch_assoc:
      case pdo::fetch_num:
      case pdo::fetch_both:
      case pdo::fetch_named:
      case pdo::fetch_obj:
        $this->_fetchmode = $mode;
        break;
      default:
        /**
         * @see zend_db_adapter_exception
         */
        require_once 'zend/db/adapter/exception.php';
        throw new zend_db_adapter_exception("invalid fetch mode '$mode' specified");
        break;
    }
  }
  /**
   * check if the adapter supports real sql parameters.
   *
   * @param string $type 'positional' or 'named'
   * @return bool
   */
  public function supportsparameters($type)
  {
    switch ($type) {
      case 'positional':
      case 'named':
      default:
        return true;
    }
  }
  /**
   * retrieve server version in php style
   *
   * @return string
   */
  public function getserverversion()
  {
    $this->_connect();
    try {
      $version = $this->_connection->getattribute(pdo::attr_server_version);
    } catch (pdoexception $e) {
      // in case of the driver doesn't support getting attributes
      return null;
    }
    $matches = null;
    if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $version, $matches)) {
      return $matches[1];
    } else {
      return null;
    }
  }
}

这个抽象类中又有另一个核心的抽象类。一些核心的方法都在这里

<?php
/**
 * zend framework
 *
 * license
 *
 * this source file is subject to the new bsd license that is bundled
 * with this package in the file license.txt.
 * it is also available through the world-wide-web at this url:
 * http://framework.zend.com/license/new-bsd
 * if you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  zend
 * @package  zend_db
 * @subpackage adapter
 * @copyright copyright (c) 2005-2012 zend technologies usa inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   new bsd license
 * @version  $id: abstract.php 25229 2013-01-18 08:17:21z frosch $
 */
/**
 * @see zend_db
 */
require_once 'zend/db.php';
/**
 * @see zend_db_select
 */
require_once 'zend/db/select.php';
/**
 * class for connecting to sql databases and performing common operations.
 *
 * @category  zend
 * @package  zend_db
 * @subpackage adapter
 * @copyright copyright (c) 2005-2012 zend technologies usa inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   new bsd license
 */
abstract class zend_db_adapter_abstract
{
  /**
   * user-provided configuration
   *
   * @var array
   */
  protected $_config = array();
  /**
   * fetch mode
   *
   * @var integer
   */
  protected $_fetchmode = zend_db::fetch_assoc;
  /**
   * query profiler object, of type zend_db_profiler
   * or a subclass of that.
   *
   * @var zend_db_profiler
   */
  protected $_profiler;
  /**
   * default class name for a db statement.
   *
   * @var string
   */
  protected $_defaultstmtclass = 'zend_db_statement';
  /**
   * default class name for the profiler object.
   *
   * @var string
   */
  protected $_defaultprofilerclass = 'zend_db_profiler';
  /**
   * database connection
   *
   * @var object|resource|null
   */
  protected $_connection = null;
  /**
   * specifies the case of column names retrieved in queries
   * options
   * zend_db::case_natural (default)
   * zend_db::case_lower
   * zend_db::case_upper
   *
   * @var integer
   */
  protected $_casefolding = zend_db::case_natural;
  /**
   * specifies whether the adapter automatically quotes identifiers.
   * if true, most sql generated by zend_db classes applies
   * identifier quoting automatically.
   * if false, developer must quote identifiers themselves
   * by calling quoteidentifier().
   *
   * @var bool
   */
  protected $_autoquoteidentifiers = true;
  /**
   * keys are uppercase sql datatypes or the constants
   * zend_db::int_type, zend_db::bigint_type, or zend_db::float_type.
   *
   * values are:
   * 0 = 32-bit integer
   * 1 = 64-bit integer
   * 2 = float or decimal
   *
   * @var array associative array of datatypes to values 0, 1, or 2.
   */
  protected $_numericdatatypes = array(
    zend_db::int_type  => zend_db::int_type,
    zend_db::bigint_type => zend_db::bigint_type,
    zend_db::float_type => zend_db::float_type
  );
  /** weither or not that object can get serialized
   *
   * @var bool
   */
  protected $_allowserialization = true;
  /**
   * weither or not the database should be reconnected
   * to that adapter when waking up
   *
   * @var bool
   */
  protected $_autoreconnectonunserialize = false;
  /**
   * constructor.
   *
   * $config is an array of key/value pairs or an instance of zend_config
   * containing configuration options. these options are common to most adapters:
   *
   * dbname     => (string) the name of the database to user
   * username    => (string) connect to the database as this username.
   * password    => (string) password associated with the username.
   * host      => (string) what host to connect to, defaults to localhost
   *
   * some options are used on a case-by-case basis by adapters:
   *
   * port      => (string) the port of the database
   * persistent   => (boolean) whether to use a persistent connection or not, defaults to false
   * protocol    => (string) the network protocol, defaults to tcpip
   * casefolding  => (int) style of case-alteration used for identifiers
   * socket     => (string) the socket or named pipe that should be used
   *
   * @param array|zend_config $config an array or instance of zend_config having configuration data
   * @throws zend_db_adapter_exception
   */
  public function __construct($config)
  {
    /*
     * verify that adapter parameters are in an array.
     */
    if (!is_array($config)) {
      /*
       * convert zend_config argument to a plain array.
       */
      if ($config instanceof zend_config) {
        $config = $config->toarray();
      } else {
        /**
         * @see zend_db_adapter_exception
         */
        require_once 'zend/db/adapter/exception.php';
        throw new zend_db_adapter_exception('adapter parameters must be in an array or a zend_config object');
      }
    }
    $this->_checkrequiredoptions($config);
    $options = array(
      zend_db::case_folding      => $this->_casefolding,
      zend_db::auto_quote_identifiers => $this->_autoquoteidentifiers,
      zend_db::fetch_mode       => $this->_fetchmode,
    );
    $driveroptions = array();
    /*
     * normalize the config and merge it with the defaults
     */
    if (array_key_exists('options', $config)) {
      // can't use array_merge() because keys might be integers
      foreach ((array) $config['options'] as $key => $value) {
        $options[$key] = $value;
      }
    }
    if (array_key_exists('driver_options', $config)) {
      if (!empty($config['driver_options'])) {
        // can't use array_merge() because keys might be integers
        foreach ((array) $config['driver_options'] as $key => $value) {
          $driveroptions[$key] = $value;
        }
      }
    }
    if (!isset($config['charset'])) {
      $config['charset'] = null;
    }
    if (!isset($config['persistent'])) {
      $config['persistent'] = false;
    }
    $this->_config = array_merge($this->_config, $config);
    $this->_config['options'] = $options;
    $this->_config['driver_options'] = $driveroptions;
    // obtain the case setting, if there is one
    if (array_key_exists(zend_db::case_folding, $options)) {
      $case = (int) $options[zend_db::case_folding];
      switch ($case) {
        case zend_db::case_lower:
        case zend_db::case_upper:
        case zend_db::case_natural:
          $this->_casefolding = $case;
          break;
        default:
          /** @see zend_db_adapter_exception */
          require_once 'zend/db/adapter/exception.php';
          throw new zend_db_adapter_exception('case must be one of the following constants: '
            . 'zend_db::case_natural, zend_db::case_lower, zend_db::case_upper');
      }
    }
    if (array_key_exists(zend_db::fetch_mode, $options)) {
      if (is_string($options[zend_db::fetch_mode])) {
        $constant = 'zend_db::fetch_' . strtoupper($options[zend_db::fetch_mode]);
        if(defined($constant)) {
          $options[zend_db::fetch_mode] = constant($constant);
        }
      }
      $this->setfetchmode((int) $options[zend_db::fetch_mode]);
    }
    // obtain quoting property if there is one
    if (array_key_exists(zend_db::auto_quote_identifiers, $options)) {
      $this->_autoquoteidentifiers = (bool) $options[zend_db::auto_quote_identifiers];
    }
    // obtain allow serialization property if there is one
    if (array_key_exists(zend_db::allow_serialization, $options)) {
      $this->_allowserialization = (bool) $options[zend_db::allow_serialization];
    }
    // obtain auto reconnect on unserialize property if there is one
    if (array_key_exists(zend_db::auto_reconnect_on_unserialize, $options)) {
      $this->_autoreconnectonunserialize = (bool) $options[zend_db::auto_reconnect_on_unserialize];
    }
    // create a profiler object
    $profiler = false;
    if (array_key_exists(zend_db::profiler, $this->_config)) {
      $profiler = $this->_config[zend_db::profiler];
      unset($this->_config[zend_db::profiler]);
    }
    $this->setprofiler($profiler);
  }
  /**
   * check for config options that are mandatory.
   * throw exceptions if any are missing.
   *
   * @param array $config
   * @throws zend_db_adapter_exception
   */
  protected function _checkrequiredoptions(array $config)
  {
    // we need at least a dbname
    if (! array_key_exists('dbname', $config)) {
      /** @see zend_db_adapter_exception */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception("configuration array must have a key for 'dbname' that names the database instance");
    }
    if (! array_key_exists('password', $config)) {
      /**
       * @see zend_db_adapter_exception
       */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception("configuration array must have a key for 'password' for login credentials");
    }
    if (! array_key_exists('username', $config)) {
      /**
       * @see zend_db_adapter_exception
       */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception("configuration array must have a key for 'username' for login credentials");
    }
  }
  /**
   * returns the underlying database connection object or resource.
   * if not presently connected, this initiates the connection.
   *
   * @return object|resource|null
   */
  public function getconnection()
  {
    $this->_connect();
    return $this->_connection;
  }
  /**
   * returns the configuration variables in this adapter.
   *
   * @return array
   */
  public function getconfig()
  {
    return $this->_config;
  }
  /**
   * set the adapter's profiler object.
   *
   * the argument may be a boolean, an associative array, an instance of
   * zend_db_profiler, or an instance of zend_config.
   *
   * a boolean argument sets the profiler to enabled if true, or disabled if
   * false. the profiler class is the adapter's default profiler class,
   * zend_db_profiler.
   *
   * an instance of zend_db_profiler sets the adapter's instance to that
   * object. the profiler is enabled and disabled separately.
   *
   * an associative array argument may contain any of the keys 'enabled',
   * 'class', and 'instance'. the 'enabled' and 'instance' keys correspond to the
   * boolean and object types documented above. the 'class' key is used to name a
   * class to use for a custom profiler. the class must be zend_db_profiler or a
   * subclass. the class is instantiated with no constructor arguments. the 'class'
   * option is ignored when the 'instance' option is supplied.
   *
   * an object of type zend_config may contain the properties 'enabled', 'class', and
   * 'instance', just as if an associative array had been passed instead.
   *
   * @param zend_db_profiler|zend_config|array|boolean $profiler
   * @return zend_db_adapter_abstract provides a fluent interface
   * @throws zend_db_profiler_exception if the object instance or class specified
   *     is not zend_db_profiler or an extension of that class.
   */
  public function setprofiler($profiler)
  {
    $enabled     = null;
    $profilerclass  = $this->_defaultprofilerclass;
    $profilerinstance = null;
    if ($profilerisobject = is_object($profiler)) {
      if ($profiler instanceof zend_db_profiler) {
        $profilerinstance = $profiler;
      } else if ($profiler instanceof zend_config) {
        $profiler = $profiler->toarray();
      } else {
        /**
         * @see zend_db_profiler_exception
         */
        require_once 'zend/db/profiler/exception.php';
        throw new zend_db_profiler_exception('profiler argument must be an instance of either zend_db_profiler'
          . ' or zend_config when provided as an object');
      }
    }
    if (is_array($profiler)) {
      if (isset($profiler['enabled'])) {
        $enabled = (bool) $profiler['enabled'];
      }
      if (isset($profiler['class'])) {
        $profilerclass = $profiler['class'];
      }
      if (isset($profiler['instance'])) {
        $profilerinstance = $profiler['instance'];
      }
    } else if (!$profilerisobject) {
      $enabled = (bool) $profiler;
    }
    if ($profilerinstance === null) {
      if (!class_exists($profilerclass)) {
        require_once 'zend/loader.php';
        zend_loader::loadclass($profilerclass);
      }
      $profilerinstance = new $profilerclass();
    }
    if (!$profilerinstance instanceof zend_db_profiler) {
      /** @see zend_db_profiler_exception */
      require_once 'zend/db/profiler/exception.php';
      throw new zend_db_profiler_exception('class ' . get_class($profilerinstance) . ' does not extend '
        . 'zend_db_profiler');
    }
    if (null !== $enabled) {
      $profilerinstance->setenabled($enabled);
    }
    $this->_profiler = $profilerinstance;
    return $this;
  }
  /**
   * returns the profiler for this adapter.
   *
   * @return zend_db_profiler
   */
  public function getprofiler()
  {
    return $this->_profiler;
  }
  /**
   * get the default statement class.
   *
   * @return string
   */
  public function getstatementclass()
  {
    return $this->_defaultstmtclass;
  }
  /**
   * set the default statement class.
   *
   * @return zend_db_adapter_abstract fluent interface
   */
  public function setstatementclass($class)
  {
    $this->_defaultstmtclass = $class;
    return $this;
  }
  /**
   * 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;
  }
  /**
   * leave autocommit mode and begin a transaction.
   *
   * @return zend_db_adapter_abstract
   */
  public function begintransaction()
  {
    $this->_connect();
    $q = $this->_profiler->querystart('begin', zend_db_profiler::transaction);
    $this->_begintransaction();
    $this->_profiler->queryend($q);
    return $this;
  }
  /**
   * commit a transaction and return to autocommit mode.
   *
   * @return zend_db_adapter_abstract
   */
  public function commit()
  {
    $this->_connect();
    $q = $this->_profiler->querystart('commit', zend_db_profiler::transaction);
    $this->_commit();
    $this->_profiler->queryend($q);
    return $this;
  }
  /**
   * roll back a transaction and return to autocommit mode.
   *
   * @return zend_db_adapter_abstract
   */
  public function rollback()
  {
    $this->_connect();
    $q = $this->_profiler->querystart('rollback', zend_db_profiler::transaction);
    $this->_rollback();
    $this->_profiler->queryend($q);
    return $this;
  }
  /**
   * inserts a table row with specified data.
   *
   * @param mixed $table the table to insert data into.
   * @param array $bind column-value pairs.
   * @return int the number of affected rows.
   * @throws zend_db_adapter_exception
   */
  public function insert($table, array $bind)
  {
    // extract and quote col names from the array keys
    $cols = array();
    $vals = array();
    $i = 0;
    foreach ($bind as $col => $val) {
      $cols[] = $this->quoteidentifier($col, true);
      if ($val instanceof zend_db_expr) {
        $vals[] = $val->__tostring();
        unset($bind[$col]);
      } else {
        if ($this->supportsparameters('positional')) {
          $vals[] = '?';
        } else {
          if ($this->supportsparameters('named')) {
            unset($bind[$col]);
            $bind[':col'.$i] = $val;
            $vals[] = ':col'.$i;
            $i++;
          } else {
            /** @see zend_db_adapter_exception */
            require_once 'zend/db/adapter/exception.php';
            throw new zend_db_adapter_exception(get_class($this) ." doesn't support positional or named binding");
          }
        }
      }
    }
    // build the statement
    $sql = "insert into "
       . $this->quoteidentifier($table, true)
       . ' (' . implode(', ', $cols) . ') '
       . 'values (' . implode(', ', $vals) . ')';
    // execute the statement and return the number of affected rows
    if ($this->supportsparameters('positional')) {
      $bind = array_values($bind);
    }
    $stmt = $this->query($sql, $bind);
    $result = $stmt->rowcount();
    return $result;
  }
  /**
   * updates table rows with specified data based on a where clause.
   *
   * @param mixed    $table the table to update.
   * @param array    $bind column-value pairs.
   * @param mixed    $where update where clause(s).
   * @return int     the number of affected rows.
   * @throws zend_db_adapter_exception
   */
  public function update($table, array $bind, $where = '')
  {
    /**
     * build "col = ?" pairs for the statement,
     * except for zend_db_expr which is treated literally.
     */
    $set = array();
    $i = 0;
    foreach ($bind as $col => $val) {
      if ($val instanceof zend_db_expr) {
        $val = $val->__tostring();
        unset($bind[$col]);
      } else {
        if ($this->supportsparameters('positional')) {
          $val = '?';
        } else {
          if ($this->supportsparameters('named')) {
            unset($bind[$col]);
            $bind[':col'.$i] = $val;
            $val = ':col'.$i;
            $i++;
          } else {
            /** @see zend_db_adapter_exception */
            require_once 'zend/db/adapter/exception.php';
            throw new zend_db_adapter_exception(get_class($this) ." doesn't support positional or named binding");
          }
        }
      }
      $set[] = $this->quoteidentifier($col, true) . ' = ' . $val;
    }
    $where = $this->_whereexpr($where);
    /**
     * build the update statement
     */
    $sql = "update "
       . $this->quoteidentifier($table, true)
       . ' set ' . implode(', ', $set)
       . (($where) ? " where $where" : '');
    /**
     * execute the statement and return the number of affected rows
     */
    if ($this->supportsparameters('positional')) {
      $stmt = $this->query($sql, array_values($bind));
    } else {
      $stmt = $this->query($sql, $bind);
    }
    $result = $stmt->rowcount();
    return $result;
  }
  /**
   * deletes table rows based on a where clause.
   *
   * @param mixed    $table the table to update.
   * @param mixed    $where delete where clause(s).
   * @return int     the number of affected rows.
   */
  public function delete($table, $where = '')
  {
    $where = $this->_whereexpr($where);
    /**
     * build the delete statement
     */
    $sql = "delete from "
       . $this->quoteidentifier($table, true)
       . (($where) ? " where $where" : '');
    /**
     * execute the statement and return the number of affected rows
     */
    $stmt = $this->query($sql);
    $result = $stmt->rowcount();
    return $result;
  }
  /**
   * convert an array, string, or zend_db_expr object
   * into a string to put in a where clause.
   *
   * @param mixed $where
   * @return string
   */
  protected function _whereexpr($where)
  {
    if (empty($where)) {
      return $where;
    }
    if (!is_array($where)) {
      $where = array($where);
    }
    foreach ($where as $cond => &$term) {
      // is $cond an int? (i.e. not a condition)
      if (is_int($cond)) {
        // $term is the full condition
        if ($term instanceof zend_db_expr) {
          $term = $term->__tostring();
        }
      } else {
        // $cond is the condition with placeholder,
        // and $term is quoted into the condition
        $term = $this->quoteinto($cond, $term);
      }
      $term = '(' . $term . ')';
    }
    $where = implode(' and ', $where);
    return $where;
  }
  /**
   * creates and returns a new zend_db_select object for this adapter.
   *
   * @return zend_db_select
   */
  public function select()
  {
    return new zend_db_select($this);
  }
  /**
   * get the fetch mode.
   *
   * @return int
   */
  public function getfetchmode()
  {
    return $this->_fetchmode;
  }
  /**
   * fetches all sql result rows as a sequential array.
   * uses the current fetchmode for the adapter.
   *
   * @param string|zend_db_select $sql an sql select statement.
   * @param mixed         $bind data to bind into select placeholders.
   * @param mixed         $fetchmode override current fetch mode.
   * @return array
   */
  public function fetchall($sql, $bind = array(), $fetchmode = null)
  {
    if ($fetchmode === null) {
      $fetchmode = $this->_fetchmode;
    }
    $stmt = $this->query($sql, $bind);
    $result = $stmt->fetchall($fetchmode);
    return $result;
  }
  /**
   * fetches the first row of the sql result.
   * uses the current fetchmode for the adapter.
   *
   * @param string|zend_db_select $sql an sql select statement.
   * @param mixed $bind data to bind into select placeholders.
   * @param mixed         $fetchmode override current fetch mode.
   * @return mixed array, object, or scalar depending on fetch mode.
   */
  public function fetchrow($sql, $bind = array(), $fetchmode = null)
  {
    if ($fetchmode === null) {
      $fetchmode = $this->_fetchmode;
    }
    $stmt = $this->query($sql, $bind);
    $result = $stmt->fetch($fetchmode);
    return $result;
  }
  /**
   * fetches all sql result rows as an associative array.
   *
   * the first column is the key, the entire row array is the
   * value. you should construct the query to be sure that
   * the first column contains unique values, or else
   * rows with duplicate values in the first column will
   * overwrite previous data.
   *
   * @param string|zend_db_select $sql an sql select statement.
   * @param mixed $bind data to bind into select placeholders.
   * @return array
   */
  public function fetchassoc($sql, $bind = array())
  {
    $stmt = $this->query($sql, $bind);
    $data = array();
    while ($row = $stmt->fetch(zend_db::fetch_assoc)) {
      $tmp = array_values(array_slice($row, 0, 1));
      $data[$tmp[0]] = $row;
    }
    return $data;
  }
  /**
   * fetches the first column of all sql result rows as an array.
   *
   * @param string|zend_db_select $sql an sql select statement.
   * @param mixed $bind data to bind into select placeholders.
   * @return array
   */
  public function fetchcol($sql, $bind = array())
  {
    $stmt = $this->query($sql, $bind);
    $result = $stmt->fetchall(zend_db::fetch_column, 0);
    return $result;
  }
  /**
   * fetches all sql result rows as an array of key-value pairs.
   *
   * the first column is the key, the second column is the
   * value.
   *
   * @param string|zend_db_select $sql an sql select statement.
   * @param mixed $bind data to bind into select placeholders.
   * @return array
   */
  public function fetchpairs($sql, $bind = array())
  {
    $stmt = $this->query($sql, $bind);
    $data = array();
    while ($row = $stmt->fetch(zend_db::fetch_num)) {
      $data[$row[0]] = $row[1];
    }
    return $data;
  }
  /**
   * fetches the first column of the first row of the sql result.
   *
   * @param string|zend_db_select $sql an sql select statement.
   * @param mixed $bind data to bind into select placeholders.
   * @return string
   */
  public function fetchone($sql, $bind = array())
  {
    $stmt = $this->query($sql, $bind);
    $result = $stmt->fetchcolumn(0);
    return $result;
  }
  /**
   * quote a raw string.
   *
   * @param string $value   raw string
   * @return string      quoted string
   */
  protected function _quote($value)
  {
    if (is_int($value)) {
      return $value;
    } elseif (is_float($value)) {
      return sprintf('%f', $value);
    }
    return "'" . addcslashes($value, "\000\n\r\\'\"\032") . "'";
  }
  /**
   * safely quotes a value for an sql statement.
   *
   * if an array is passed as the value, the array values are quoted
   * and then returned as a comma-separated string.
   *
   * @param mixed $value the value to quote.
   * @param mixed $type optional the sql datatype name, or constant, or null.
   * @return mixed an sql-safe quoted value (or string of separated values).
   */
  public function quote($value, $type = null)
  {
    $this->_connect();
    if ($value instanceof zend_db_select) {
      return '(' . $value->assemble() . ')';
    }
    if ($value instanceof zend_db_expr) {
      return $value->__tostring();
    }
    if (is_array($value)) {
      foreach ($value as &$val) {
        $val = $this->quote($val, $type);
      }
      return implode(', ', $value);
    }
    if ($type !== null && array_key_exists($type = strtoupper($type), $this->_numericdatatypes)) {
      $quotedvalue = '0';
      switch ($this->_numericdatatypes[$type]) {
        case zend_db::int_type: // 32-bit integer
          $quotedvalue = (string) intval($value);
          break;
        case zend_db::bigint_type: // 64-bit integer
          // ansi sql-style hex literals (e.g. x'[\da-f]+')
          // are not supported here, because these are string
          // literals, not numeric literals.
          if (preg_match('/^(
             [+-]?         # optional sign
             (?:
              0[xx][\da-fa-f]+   # odbc-style hexadecimal
              |\d+         # decimal or octal, or mysql zerofill decimal
              (?:[ee][+-]?\d+)?  # optional exponent on decimals or octals
             )
            )/x',
            (string) $value, $matches)) {
            $quotedvalue = $matches[1];
          }
          break;
        case zend_db::float_type: // float or decimal
          $quotedvalue = sprintf('%f', $value);
      }
      return $quotedvalue;
    }
    return $this->_quote($value);
  }
  /**
   * quotes a value and places into a piece of text at a placeholder.
   *
   * the placeholder is a question-mark; all placeholders will be replaced
   * with the quoted value.  for example:
   *
   * <code>
   * $text = "where date < ?";
   * $date = "2005-01-02";
   * $safe = $sql->quoteinto($text, $date);
   * // $safe = "where date < '2005-01-02'"
   * </code>
   *
   * @param string $text the text with a placeholder.
   * @param mixed  $value the value to quote.
   * @param string $type optional sql datatype
   * @param integer $count optional count of placeholders to replace
   * @return string an sql-safe quoted value placed into the original text.
   */
  public function quoteinto($text, $value, $type = null, $count = null)
  {
    if ($count === null) {
      return str_replace('?', $this->quote($value, $type), $text);
    } else {
      while ($count > 0) {
        if (strpos($text, '?') !== false) {
          $text = substr_replace($text, $this->quote($value, $type), strpos($text, '?'), 1);
        }
        --$count;
      }
      return $text;
    }
  }
  /**
   * quotes an identifier.
   *
   * accepts a string representing a qualified indentifier. for example:
   * <code>
   * $adapter->quoteidentifier('myschema.mytable')
   * </code>
   * returns: "myschema"."mytable"
   *
   * or, an array of one or more identifiers that may form a qualified identifier:
   * <code>
   * $adapter->quoteidentifier(array('myschema','my.table'))
   * </code>
   * returns: "myschema"."my.table"
   *
   * the actual quote character surrounding the identifiers may vary depending on
   * the adapter.
   *
   * @param string|array|zend_db_expr $ident the identifier.
   * @param boolean $auto if true, heed the auto_quote_identifiers config option.
   * @return string the quoted identifier.
   */
  public function quoteidentifier($ident, $auto=false)
  {
    return $this->_quoteidentifieras($ident, null, $auto);
  }
  /**
   * quote a column identifier and alias.
   *
   * @param string|array|zend_db_expr $ident the identifier or expression.
   * @param string $alias an alias for the column.
   * @param boolean $auto if true, heed the auto_quote_identifiers config option.
   * @return string the quoted identifier and alias.
   */
  public function quotecolumnas($ident, $alias, $auto=false)
  {
    return $this->_quoteidentifieras($ident, $alias, $auto);
  }
  /**
   * quote a table identifier and alias.
   *
   * @param string|array|zend_db_expr $ident the identifier or expression.
   * @param string $alias an alias for the table.
   * @param boolean $auto if true, heed the auto_quote_identifiers config option.
   * @return string the quoted identifier and alias.
   */
  public function quotetableas($ident, $alias = null, $auto = false)
  {
    return $this->_quoteidentifieras($ident, $alias, $auto);
  }
  /**
   * quote an identifier and an optional alias.
   *
   * @param string|array|zend_db_expr $ident the identifier or expression.
   * @param string $alias an optional alias.
   * @param boolean $auto if true, heed the auto_quote_identifiers config option.
   * @param string $as the string to add between the identifier/expression and the alias.
   * @return string the quoted identifier and alias.
   */
  protected function _quoteidentifieras($ident, $alias = null, $auto = false, $as = ' as ')
  {
    if ($ident instanceof zend_db_expr) {
      $quoted = $ident->__tostring();
    } elseif ($ident instanceof zend_db_select) {
      $quoted = '(' . $ident->assemble() . ')';
    } else {
      if (is_string($ident)) {
        $ident = explode('.', $ident);
      }
      if (is_array($ident)) {
        $segments = array();
        foreach ($ident as $segment) {
          if ($segment instanceof zend_db_expr) {
            $segments[] = $segment->__tostring();
          } else {
            $segments[] = $this->_quoteidentifier($segment, $auto);
          }
        }
        if ($alias !== null && end($ident) == $alias) {
          $alias = null;
        }
        $quoted = implode('.', $segments);
      } else {
        $quoted = $this->_quoteidentifier($ident, $auto);
      }
    }
    if ($alias !== null) {
      $quoted .= $as . $this->_quoteidentifier($alias, $auto);
    }
    return $quoted;
  }
  /**
   * quote an identifier.
   *
   * @param string $value the identifier or expression.
   * @param boolean $auto if true, heed the auto_quote_identifiers config option.
   * @return string    the quoted identifier and alias.
   */
  protected function _quoteidentifier($value, $auto=false)
  {
    if ($auto === false || $this->_autoquoteidentifiers === true) {
      $q = $this->getquoteidentifiersymbol();
      return ($q . str_replace("$q", "$q$q", $value) . $q);
    }
    return $value;
  }
  /**
   * returns the symbol the adapter uses for delimited identifiers.
   *
   * @return string
   */
  public function getquoteidentifiersymbol()
  {
    return '"';
  }
  /**
   * return the most recent value from the specified sequence in the database.
   * this is supported only on rdbms brands that support sequences
   * (e.g. oracle, postgresql, db2). other rdbms brands return null.
   *
   * @param string $sequencename
   * @return string
   */
  public function lastsequenceid($sequencename)
  {
    return null;
  }
  /**
   * generate a new value from the specified sequence in the database, and return it.
   * this is supported only on rdbms brands that support sequences
   * (e.g. oracle, postgresql, db2). other rdbms brands return null.
   *
   * @param string $sequencename
   * @return string
   */
  public function nextsequenceid($sequencename)
  {
    return null;
  }
  /**
   * helper method to change the case of the strings used
   * when returning result sets in fetch_assoc and fetch_both
   * modes.
   *
   * this is not intended to be used by application code,
   * but the method must be public so the statement class
   * can invoke it.
   *
   * @param string $key
   * @return string
   */
  public function foldcase($key)
  {
    switch ($this->_casefolding) {
      case zend_db::case_lower:
        $value = strtolower((string) $key);
        break;
      case zend_db::case_upper:
        $value = strtoupper((string) $key);
        break;
      case zend_db::case_natural:
      default:
        $value = (string) $key;
    }
    return $value;
  }
  /**
   * called when object is getting serialized
   * this disconnects the db object that cant be serialized
   *
   * @throws zend_db_adapter_exception
   * @return array
   */
  public function __sleep()
  {
    if ($this->_allowserialization == false) {
      /** @see zend_db_adapter_exception */
      require_once 'zend/db/adapter/exception.php';
      throw new zend_db_adapter_exception(get_class($this) ." is not allowed to be serialized");
    }
    $this->_connection = false;
    return array_keys(array_diff_key(get_object_vars($this), array('_connection'=>false)));
  }
  /**
   * called when object is getting unserialized
   *
   * @return void
   */
  public function __wakeup()
  {
    if ($this->_autoreconnectonunserialize == true) {
      $this->getconnection();
    }
  }
  /**
   * abstract methods
   */
  /**
   * returns a list of the tables in the database.
   *
   * @return array
   */
  abstract public function listtables();
  /**
   * returns the column descriptions for a table.
   *
   * the return value is an associative array keyed by the column name,
   * as returned by the rdbms.
   *
   * the value of each array element is an associative array
   * with the following keys:
   *
   * schema_name => string; name of database or schema
   * table_name => string;
   * column_name => string; column name
   * column_position => number; ordinal position of column in table
   * data_type  => string; sql datatype name of column
   * default   => string; default expression of column, null if none
   * nullable  => boolean; true if column can have nulls
   * length   => number; length of char/varchar
   * scale    => number; scale of numeric/decimal
   * precision  => number; precision of numeric/decimal
   * unsigned  => boolean; unsigned property of an integer type
   * primary   => boolean; true if column is part of the primary key
   * primary_position => integer; position of column in primary key
   *
   * @param string $tablename
   * @param string $schemaname optional
   * @return array
   */
  abstract public function describetable($tablename, $schemaname = null);
  /**
   * creates a connection to the database.
   *
   * @return void
   */
  abstract protected function _connect();
  /**
   * test if a connection is active
   *
   * @return boolean
   */
  abstract public function isconnected();
  /**
   * force the connection to close.
   *
   * @return void
   */
  abstract public function closeconnection();
  /**
   * prepare a statement and return a pdostatement-like object.
   *
   * @param string|zend_db_select $sql sql query
   * @return zend_db_statement|pdostatement
   */
  abstract public function prepare($sql);
  /**
   * gets the last id generated automatically by an identity/autoincrement column.
   *
   * as a convention, on rdbms brands that support sequences
   * (e.g. oracle, postgresql, db2), this method forms the name of a sequence
   * from the arguments and returns the last id generated by that sequence.
   * on rdbms brands that support identity/autoincrement columns, this method
   * returns the last value generated for such a column, and the table name
   * argument is disregarded.
   *
   * @param string $tablename  optional name of table.
   * @param string $primarykey optional name of primary key column.
   * @return string
   */
  abstract public function lastinsertid($tablename = null, $primarykey = null);
  /**
   * begin a transaction.
   */
  abstract protected function _begintransaction();
  /**
   * commit a transaction.
   */
  abstract protected function _commit();
  /**
   * roll-back a transaction.
   */
  abstract protected function _rollback();
  /**
   * set the fetch mode.
   *
   * @param integer $mode
   * @return void
   * @throws zend_db_adapter_exception
   */
  abstract public function setfetchmode($mode);
  /**
   * adds an adapter-specific limit clause to the select statement.
   *
   * @param mixed $sql
   * @param integer $count
   * @param integer $offset
   * @return string
   */
  abstract public function limit($sql, $count, $offset = 0);
  /**
   * check if the adapter supports real sql parameters.
   *
   * @param string $type 'positional' or 'named'
   * @return bool
   */
  abstract public function supportsparameters($type);
  /**
   * retrieve server version in php style
   *
   * @return string
   */
  abstract public function getserverversion();
}

到此,我已经晕了。你呢???

哈哈哈。。。

下面看一些简单的案例

插入数据到数据库:

<?php
require_once 'zend/db.php';
$params = array('host'=>'127.0.0.1',
  'username'=>'root',
  'password'=>'',
  'dbname'=>'test'
  );
$db = zend_db::factory('pdo_mysql',$params);
$row = array(
  'username'=>'jiqing',
  'password'=>'jiqing90061234'
  );
$table = 'user';
$res = $db->insert($table,$row);
if($res){
  echo "成功插入新的记录!";
  echo "<p>";
  $last_insert_id = $db->lastinsertid($table);
  echo "新记录的id值为:";
  echo $last_insert_id;
  echo "<p>";
  echo "其内容为:";
  $sql = "select * from $table where id=$last_insert_id";
  $result = $db->fetchrow($sql);
  echo "<p>";
  foreach($result as $key=>$val){
    echo $key;
    echo "值为:";
    echo $val;
    echo "<p>";
  }
}else{
  echo "插入数据有误";
}

结果为:

成功插入新的记录!
新记录的id值为:13
其内容为:
id值为:13
username值为:jiqing
password值为:jiqing90061234

修改update方法

删除delete方法

都大同小异,首先连接数据库,然后填写相应参数,执行即可。

查询方法总结:

fetchall()匹配查询结果,返回一个连续的数组。
fetchassoc()匹配查询结果,返回一个联合的数组。
fetchcol()匹配结果的第一列,返回一个数组。
fetchone()陪陪查询结果的第一列与第一行的值,返回一个字符串。
fetchrow()匹配查询结果的第一行,返回一个数组。

常用的是第一个和最后一个方法,其他的方法用的不是很多。

更多关于zend相关内容感兴趣的读者可查看本站专题:《zend framework框架入门教程》、《php优秀开发框架总结》、《yii框架入门及常用技巧总结》、《thinkphp入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于zend framework框架的php程序设计有所帮助。