Zend Framework入门教程之Zend_Db数据库操作详解
本文实例讲述了ZendFramework中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*FROMuserWHEREid<?','5');
$result=$db->query($sql);//执行SQL查询
$r_a=$result->fetchAll();//返回结果数组
print_r($r_a);
点评:
执行完上述代码,就会展示出数据库中前五条记录的信息。
那么这其中的玄机是什么呢?
我们来看一下源码。
我们来看看Db.php中的factory方法
publicstaticfunctionfactory($adapter,$config=array())
{
if($configinstanceofZend_Config){
$config=$config->toArray();
}
/*
*ConvertZend_Configargumenttoplainstring
*adapternameandseparateconfigobject.
*/
if($adapterinstanceofZend_Config){
if(isset($adapter->params)){
$config=$adapter->params->toArray();
}
if(isset($adapter->adapter)){
$adapter=(string)$adapter->adapter;
}else{
$adapter=null;
}
}
/*
*Verifythatadapterparametersareinanarray.
*/
if(!is_array($config)){
/**
*@seeZend_Db_Exception
*/
require_once'Zend/Db/Exception.php';
thrownewZend_Db_Exception('AdapterparametersmustbeinanarrayoraZend_Configobject');
}
/*
*Verifythatanadapternamehasbeenspecified.
*/
if(!is_string($adapter)||empty($adapter)){
/**
*@seeZend_Db_Exception
*/
require_once'Zend/Db/Exception.php';
thrownewZend_Db_Exception('Adapternamemustbespecifiedinastring');
}
/*
*Formfulladapterclassname
*/
$adapterNamespace='Zend_Db_Adapter';
if(isset($config['adapterNamespace'])){
if($config['adapterNamespace']!=''){
$adapterNamespace=$config['adapterNamespace'];
}
unset($config['adapterNamespace']);
}
//Adapternolongernormalized-seehttp://framework.zend.com/issues/browse/ZF-5606
$adapterName=$adapterNamespace.'_';
$adapterName.=str_replace('','_',ucwords(str_replace('_','',strtolower($adapter))));
print_r($adapterName);exit;
/*
*Loadtheadapterclass.Thisthrowsanexception
*ifthespecifiedclasscannotbeloaded.
*/
if(!class_exists($adapterName)){
require_once'Zend/Loader.php';
Zend_Loader::loadClass($adapterName);
}
/*
*Createaninstanceoftheadapterclass.
*Passtheconfigtotheadapterclassconstructor.
*/
$dbAdapter=new$adapterName($config);
/*
*Verifythattheobjectcreatedisadescendentoftheabstractadaptertype.
*/
if(!$dbAdapterinstanceofZend_Db_Adapter_Abstract){
/**
*@seeZend_Db_Exception
*/
require_once'Zend/Db/Exception.php';
thrownewZend_Db_Exception("Adapterclass'$adapterName'doesnotextendZend_Db_Adapter_Abstract");
}
return$dbAdapter;
}
点评:这个方法就是核心了,代码量不多,但是作用很明确,它会通过你提供的两个参数,自动生成相应的数据库连接类的对象。具有一定的灵活性,机动性。
主要是其中的
$adapterName=$adapterNamespace.'_';
$adapterName.=str_replace('','_',ucwords(str_replace('_','',strtolower($adapter))));
/*
*Loadtheadapterclass.Thisthrowsanexception
*ifthespecifiedclasscannotbeloaded.
*/
if(!class_exists($adapterName)){
require_once'Zend/Loader.php';
Zend_Loader::loadClass($adapterName);
}
这段代码会引入相应的数据库连接类,比如前面的两个例子,就是分别引入了Zend目录下Db目录下Adapter目录下Pdo目录下的mysql.php类。
不同的数据库,会引入不同的数据库文件。
我们来看看mysql.php类中的内容:
<?php
/**
*ZendFramework
*
*LICENSE
*
*ThissourcefileissubjecttothenewBSDlicensethatisbundled
*withthispackageinthefileLICENSE.txt.
*Itisalsoavailablethroughtheworld-wide-webatthisURL:
*http://framework.zend.com/license/new-bsd
*Ifyoudidnotreceiveacopyofthelicenseandareunableto
*obtainitthroughtheworld-wide-web,pleasesendanemail
*tolicense@zend.comsowecansendyouacopyimmediately.
*
*@categoryZend
*@packageZend_Db
*@subpackageAdapter
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*@version$Id:Mysql.php245932012-01-0520:35:02Zmatthew$
*/
/**
*@seeZend_Db_Adapter_Pdo_Abstract
*/
require_once'Zend/Db/Adapter/Pdo/Abstract.php';
/**
*ClassforconnectingtoMySQLdatabasesandperformingcommonoperations.
*
*@categoryZend
*@packageZend_Db
*@subpackageAdapter
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*/
classZend_Db_Adapter_Pdo_MysqlextendsZend_Db_Adapter_Pdo_Abstract
{
/**
*PDOtype.
*
*@varstring
*/
protected$_pdoType='mysql';
/**
*KeysareUPPERCASESQLdatatypesortheconstants
*Zend_Db::INT_TYPE,Zend_Db::BIGINT_TYPE,orZend_Db::FLOAT_TYPE.
*
*Valuesare:
*0=32-bitinteger
*1=64-bitinteger
*2=floatordecimal
*
*@vararrayAssociativearrayofdatatypestovalues0,1,or2.
*/
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,
'DOUBLEPRECISION'=>Zend_Db::FLOAT_TYPE,
'FIXED'=>Zend_Db::FLOAT_TYPE,
'FLOAT'=>Zend_Db::FLOAT_TYPE
);
/**
*Override_dsn()andensurethatcharsetisincorporatedinmysql
*@seeZend_Db_Adapter_Pdo_Abstract::_dsn()
*/
protectedfunction_dsn()
{
$dsn=parent::_dsn();
if(isset($this->_config['charset'])){
$dsn.=';charset='.$this->_config['charset'];
}
return$dsn;
}
/**
*CreatesaPDOobjectandconnectstothedatabase.
*
*@returnvoid
*@throwsZend_Db_Adapter_Exception
*/
protectedfunction_connect()
{
if($this->_connection){
return;
}
if(!empty($this->_config['charset'])){
$initCommand="SETNAMES'".$this->_config['charset']."'";
$this->_config['driver_options'][1002]=$initCommand;//1002=PDO::MYSQL_ATTR_INIT_COMMAND
}
parent::_connect();
}
/**
*@returnstring
*/
publicfunctiongetQuoteIdentifierSymbol()
{
return"`";
}
/**
*Returnsalistofthetablesinthedatabase.
*
*@returnarray
*/
publicfunctionlistTables()
{
return$this->fetchCol('SHOWTABLES');
}
/**
*Returnsthecolumndescriptionsforatable.
*
*Thereturnvalueisanassociativearraykeyedbythecolumnname,
*asreturnedbytheRDBMS.
*
*Thevalueofeacharrayelementisanassociativearray
*withthefollowingkeys:
*
*SCHEMA_NAME=>string;nameofdatabaseorschema
*TABLE_NAME=>string;
*COLUMN_NAME=>string;columnname
*COLUMN_POSITION=>number;ordinalpositionofcolumnintable
*DATA_TYPE=>string;SQLdatatypenameofcolumn
*DEFAULT=>string;defaultexpressionofcolumn,nullifnone
*NULLABLE=>boolean;trueifcolumncanhavenulls
*LENGTH=>number;lengthofCHAR/VARCHAR
*SCALE=>number;scaleofNUMERIC/DECIMAL
*PRECISION=>number;precisionofNUMERIC/DECIMAL
*UNSIGNED=>boolean;unsignedpropertyofanintegertype
*PRIMARY=>boolean;trueifcolumnispartoftheprimarykey
*PRIMARY_POSITION=>integer;positionofcolumninprimarykey
*IDENTITY=>integer;trueifcolumnisauto-generatedwithuniquevalues
*
*@paramstring$tableName
*@paramstring$schemaNameOPTIONAL
*@returnarray
*/
publicfunctiondescribeTable($tableName,$schemaName=null)
{
//@todouseINFORMATION_SCHEMAsomedaywhenMySQL's
//implementationhasreasonablygoodperformanceand
//theversionwiththisimprovementisinwideuse.
if($schemaName){
$sql='DESCRIBE'.$this->quoteIdentifier("$schemaName.$tableName",true);
}else{
$sql='DESCRIBE'.$this->quoteIdentifier($tableName,true);
}
$stmt=$this->query($sql);
//UseFETCH_NUMsowearenotdependentontheCASEattributeofthePDOconnection
$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($resultas$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];
}elseif(preg_match('/^decimal\((\d+),(\d+)\)/',$row[$type],$matches)){
$row[$type]='decimal';
$precision=$matches[1];
$scale=$matches[2];
}elseif(preg_match('/^float\((\d+),(\d+)\)/',$row[$type],$matches)){
$row[$type]='float';
$precision=$matches[1];
$scale=$matches[2];
}elseif(preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/',$row[$type],$matches)){
$row[$type]=$matches[1];
//TheoptionalargumentofaMySQLinttypeisnotprecision
//orlength;itisonlyahintfordisplaywidth.
}
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;
}
/**
*Addsanadapter-specificLIMITclausetotheSELECTstatement.
*
*@paramstring$sql
*@paraminteger$count
*@paraminteger$offsetOPTIONAL
*@throwsZend_Db_Adapter_Exception
*@returnstring
*/
publicfunctionlimit($sql,$count,$offset=0)
{
$count=intval($count);
if($count<=0){
/**@seeZend_Db_Adapter_Exception*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception("LIMITargumentcount=$countisnotvalid");
}
$offset=intval($offset);
if($offset<0){
/**@seeZend_Db_Adapter_Exception*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception("LIMITargumentoffset=$offsetisnotvalid");
}
$sql.="LIMIT$count";
if($offset>0){
$sql.="OFFSET$offset";
}
return$sql;
}
}
这里又引入了一个Abstract类,抽象类
<?php
/**
*ZendFramework
*
*LICENSE
*
*ThissourcefileissubjecttothenewBSDlicensethatisbundled
*withthispackageinthefileLICENSE.txt.
*Itisalsoavailablethroughtheworld-wide-webatthisURL:
*http://framework.zend.com/license/new-bsd
*Ifyoudidnotreceiveacopyofthelicenseandareunableto
*obtainitthroughtheworld-wide-web,pleasesendanemail
*tolicense@zend.comsowecansendyouacopyimmediately.
*
*@categoryZend
*@packageZend_Db
*@subpackageAdapter
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*@version$Id:Abstract.php245932012-01-0520:35:02Zmatthew$
*/
/**
*@seeZend_Db_Adapter_Abstract
*/
require_once'Zend/Db/Adapter/Abstract.php';
/**
*@seeZend_Db_Statement_Pdo
*/
require_once'Zend/Db/Statement/Pdo.php';
/**
*ClassforconnectingtoSQLdatabasesandperformingcommonoperationsusingPDO.
*
*@categoryZend
*@packageZend_Db
*@subpackageAdapter
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*/
abstractclassZend_Db_Adapter_Pdo_AbstractextendsZend_Db_Adapter_Abstract
{
/**
*DefaultclassnameforaDBstatement.
*
*@varstring
*/
protected$_defaultStmtClass='Zend_Db_Statement_Pdo';
/**
*CreatesaPDODSNfortheadapterfrom$this->_configsettings.
*
*@returnstring
*/
protectedfunction_dsn()
{
//baselineofDSNparts
$dsn=$this->_config;
//don'tpasstheusername,password,charset,persistentanddriver_optionsintheDSN
unset($dsn['username']);
unset($dsn['password']);
unset($dsn['options']);
unset($dsn['charset']);
unset($dsn['persistent']);
unset($dsn['driver_options']);
//useallremainingpartsintheDSN
foreach($dsnas$key=>$val){
$dsn[$key]="$key=$val";
}
return$this->_pdoType.':'.implode(';',$dsn);
}
/**
*CreatesaPDOobjectandconnectstothedatabase.
*
*@returnvoid
*@throwsZend_Db_Adapter_Exception
*/
protectedfunction_connect()
{
//ifwealreadyhaveaPDOobject,noneedtore-connect.
if($this->_connection){
return;
}
//getthedsnfirst,becausesomeadaptersalterthe$_pdoType
$dsn=$this->_dsn();
//checkforPDOextension
if(!extension_loaded('pdo')){
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception('ThePDOextensionisrequiredforthisadapterbuttheextensionisnotloaded');
}
//checkthePDOdriverisavailable
if(!in_array($this->_pdoType,PDO::getAvailableDrivers())){
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception('The'.$this->_pdoType.'driverisnotcurrentlyinstalled');
}
//createPDOconnection
$q=$this->_profiler->queryStart('connect',Zend_Db_Profiler::CONNECT);
//addthepersistenceflagifwefinditinourconfigarray
if(isset($this->_config['persistent'])&&($this->_config['persistent']==true)){
$this->_config['driver_options'][PDO::ATTR_PERSISTENT]=true;
}
try{
$this->_connection=newPDO(
$dsn,
$this->_config['username'],
$this->_config['password'],
$this->_config['driver_options']
);
$this->_profiler->queryEnd($q);
//setthePDOconnectiontoperformcase-foldingonarraykeys,ornot
$this->_connection->setAttribute(PDO::ATTR_CASE,$this->_caseFolding);
//alwaysuseexceptions.
$this->_connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException$e){
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception($e->getMessage(),$e->getCode(),$e);
}
}
/**
*Testifaconnectionisactive
*
*@returnboolean
*/
publicfunctionisConnected()
{
return((bool)($this->_connectioninstanceofPDO));
}
/**
*Forcetheconnectiontoclose.
*
*@returnvoid
*/
publicfunctioncloseConnection()
{
$this->_connection=null;
}
/**
*PreparesanSQLstatement.
*
*@paramstring$sqlTheSQLstatementwithplaceholders.
*@paramarray$bindAnarrayofdatatobindtotheplaceholders.
*@returnPDOStatement
*/
publicfunctionprepare($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;
}
/**
*GetsthelastIDgeneratedautomaticallybyanIDENTITY/AUTOINCREMENTcolumn.
*
*Asaconvention,onRDBMSbrandsthatsupportsequences
*(e.g.Oracle,PostgreSQL,DB2),thismethodformsthenameofasequence
*fromtheargumentsandreturnsthelastidgeneratedbythatsequence.
*OnRDBMSbrandsthatsupportIDENTITY/AUTOINCREMENTcolumns,thismethod
*returnsthelastvaluegeneratedforsuchacolumn,andthetablename
*argumentisdisregarded.
*
*OnRDBMSbrandsthatdon'tsupportsequences,$tableNameand$primaryKey
*areignored.
*
*@paramstring$tableNameOPTIONALNameoftable.
*@paramstring$primaryKeyOPTIONALNameofprimarykeycolumn.
*@returnstring
*/
publicfunctionlastInsertId($tableName=null,$primaryKey=null)
{
$this->_connect();
return$this->_connection->lastInsertId();
}
/**
*SpecialhandlingforPDOquery().
*Allbindparameternamesmustbeginwith':'
*
*@paramstring|Zend_Db_Select$sqlTheSQLstatementwithplaceholders.
*@paramarray$bindAnarrayofdatatobindtotheplaceholders.
*@returnZend_Db_Statement_Pdo
*@throwsZend_Db_Adapter_ExceptionTore-throwPDOException.
*/
publicfunctionquery($sql,$bind=array())
{
if(empty($bind)&&$sqlinstanceofZend_Db_Select){
$bind=$sql->getBind();
}
if(is_array($bind)){
foreach($bindas$name=>$value){
if(!is_int($name)&&!preg_match('/^:/',$name)){
$newName=":$name";
unset($bind[$name]);
$bind[$newName]=$value;
}
}
}
try{
returnparent::query($sql,$bind);
}catch(PDOException$e){
/**
*@seeZend_Db_Statement_Exception
*/
require_once'Zend/Db/Statement/Exception.php';
thrownewZend_Db_Statement_Exception($e->getMessage(),$e->getCode(),$e);
}
}
/**
*ExecutesanSQLstatementandreturnthenumberofaffectedrows
*
*@parammixed$sqlTheSQLstatementwithplaceholders.
*MaybeastringorZend_Db_Select.
*@returnintegerNumberofrowsthatweremodified
*ordeletedbytheSQLstatement
*/
publicfunctionexec($sql)
{
if($sqlinstanceofZend_Db_Select){
$sql=$sql->assemble();
}
try{
$affected=$this->getConnection()->exec($sql);
if($affected===false){
$errorInfo=$this->getConnection()->errorInfo();
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception($errorInfo[2]);
}
return$affected;
}catch(PDOException$e){
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception($e->getMessage(),$e->getCode(),$e);
}
}
/**
*Quotearawstring.
*
*@paramstring$valueRawstring
*@returnstringQuotedstring
*/
protectedfunction_quote($value)
{
if(is_int($value)||is_float($value)){
return$value;
}
$this->_connect();
return$this->_connection->quote($value);
}
/**
*Beginatransaction.
*/
protectedfunction_beginTransaction()
{
$this->_connect();
$this->_connection->beginTransaction();
}
/**
*Commitatransaction.
*/
protectedfunction_commit()
{
$this->_connect();
$this->_connection->commit();
}
/**
*Roll-backatransaction.
*/
protectedfunction_rollBack(){
$this->_connect();
$this->_connection->rollBack();
}
/**
*SetthePDOfetchmode.
*
*@todoSupportFETCH_CLASSandFETCH_INTO.
*
*@paramint$modeAPDOfetchmode.
*@returnvoid
*@throwsZend_Db_Adapter_Exception
*/
publicfunctionsetFetchMode($mode)
{
//checkforPDOextension
if(!extension_loaded('pdo')){
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception('ThePDOextensionisrequiredforthisadapterbuttheextensionisnotloaded');
}
switch($mode){
casePDO::FETCH_LAZY:
casePDO::FETCH_ASSOC:
casePDO::FETCH_NUM:
casePDO::FETCH_BOTH:
casePDO::FETCH_NAMED:
casePDO::FETCH_OBJ:
$this->_fetchMode=$mode;
break;
default:
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception("Invalidfetchmode'$mode'specified");
break;
}
}
/**
*CheckiftheadaptersupportsrealSQLparameters.
*
*@paramstring$type'positional'or'named'
*@returnbool
*/
publicfunctionsupportsParameters($type)
{
switch($type){
case'positional':
case'named':
default:
returntrue;
}
}
/**
*RetrieveserverversioninPHPstyle
*
*@returnstring
*/
publicfunctiongetServerVersion()
{
$this->_connect();
try{
$version=$this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
}catch(PDOException$e){
//Incaseofthedriverdoesn'tsupportgettingattributes
returnnull;
}
$matches=null;
if(preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/',$version,$matches)){
return$matches[1];
}else{
returnnull;
}
}
}
这个抽象类中又有另一个核心的抽象类。一些核心的方法都在这里
<?php
/**
*ZendFramework
*
*LICENSE
*
*ThissourcefileissubjecttothenewBSDlicensethatisbundled
*withthispackageinthefileLICENSE.txt.
*Itisalsoavailablethroughtheworld-wide-webatthisURL:
*http://framework.zend.com/license/new-bsd
*Ifyoudidnotreceiveacopyofthelicenseandareunableto
*obtainitthroughtheworld-wide-web,pleasesendanemail
*tolicense@zend.comsowecansendyouacopyimmediately.
*
*@categoryZend
*@packageZend_Db
*@subpackageAdapter
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*@version$Id:Abstract.php252292013-01-1808:17:21Zfrosch$
*/
/**
*@seeZend_Db
*/
require_once'Zend/Db.php';
/**
*@seeZend_Db_Select
*/
require_once'Zend/Db/Select.php';
/**
*ClassforconnectingtoSQLdatabasesandperformingcommonoperations.
*
*@categoryZend
*@packageZend_Db
*@subpackageAdapter
*@copyrightCopyright(c)2005-2012ZendTechnologiesUSAInc.(http://www.zend.com)
*@licensehttp://framework.zend.com/license/new-bsdNewBSDLicense
*/
abstractclassZend_Db_Adapter_Abstract
{
/**
*User-providedconfiguration
*
*@vararray
*/
protected$_config=array();
/**
*Fetchmode
*
*@varinteger
*/
protected$_fetchMode=Zend_Db::FETCH_ASSOC;
/**
*Queryprofilerobject,oftypeZend_Db_Profiler
*orasubclassofthat.
*
*@varZend_Db_Profiler
*/
protected$_profiler;
/**
*DefaultclassnameforaDBstatement.
*
*@varstring
*/
protected$_defaultStmtClass='Zend_Db_Statement';
/**
*Defaultclassnamefortheprofilerobject.
*
*@varstring
*/
protected$_defaultProfilerClass='Zend_Db_Profiler';
/**
*Databaseconnection
*
*@varobject|resource|null
*/
protected$_connection=null;
/**
*Specifiesthecaseofcolumnnamesretrievedinqueries
*Options
*Zend_Db::CASE_NATURAL(default)
*Zend_Db::CASE_LOWER
*Zend_Db::CASE_UPPER
*
*@varinteger
*/
protected$_caseFolding=Zend_Db::CASE_NATURAL;
/**
*Specifieswhethertheadapterautomaticallyquotesidentifiers.
*Iftrue,mostSQLgeneratedbyZend_Dbclassesapplies
*identifierquotingautomatically.
*Iffalse,developermustquoteidentifiersthemselves
*bycallingquoteIdentifier().
*
*@varbool
*/
protected$_autoQuoteIdentifiers=true;
/**
*KeysareUPPERCASESQLdatatypesortheconstants
*Zend_Db::INT_TYPE,Zend_Db::BIGINT_TYPE,orZend_Db::FLOAT_TYPE.
*
*Valuesare:
*0=32-bitinteger
*1=64-bitinteger
*2=floatordecimal
*
*@vararrayAssociativearrayofdatatypestovalues0,1,or2.
*/
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
);
/**Weitherornotthatobjectcangetserialized
*
*@varbool
*/
protected$_allowSerialization=true;
/**
*Weitherornotthedatabaseshouldbereconnected
*tothatadapterwhenwakingup
*
*@varbool
*/
protected$_autoReconnectOnUnserialize=false;
/**
*Constructor.
*
*$configisanarrayofkey/valuepairsoraninstanceofZend_Config
*containingconfigurationoptions.Theseoptionsarecommontomostadapters:
*
*dbname=>(string)Thenameofthedatabasetouser
*username=>(string)Connecttothedatabaseasthisusername.
*password=>(string)Passwordassociatedwiththeusername.
*host=>(string)Whathosttoconnectto,defaultstolocalhost
*
*Someoptionsareusedonacase-by-casebasisbyadapters:
*
*port=>(string)Theportofthedatabase
*persistent=>(boolean)Whethertouseapersistentconnectionornot,defaultstofalse
*protocol=>(string)Thenetworkprotocol,defaultstoTCPIP
*caseFolding=>(int)styleofcase-alterationusedforidentifiers
*socket=>(string)Thesocketornamedpipethatshouldbeused
*
*@paramarray|Zend_Config$configAnarrayorinstanceofZend_Confighavingconfigurationdata
*@throwsZend_Db_Adapter_Exception
*/
publicfunction__construct($config)
{
/*
*Verifythatadapterparametersareinanarray.
*/
if(!is_array($config)){
/*
*ConvertZend_Configargumenttoaplainarray.
*/
if($configinstanceofZend_Config){
$config=$config->toArray();
}else{
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception('AdapterparametersmustbeinanarrayoraZend_Configobject');
}
}
$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();
/*
*normalizetheconfigandmergeitwiththedefaults
*/
if(array_key_exists('options',$config)){
//can'tusearray_merge()becausekeysmightbeintegers
foreach((array)$config['options']as$key=>$value){
$options[$key]=$value;
}
}
if(array_key_exists('driver_options',$config)){
if(!empty($config['driver_options'])){
//can'tusearray_merge()becausekeysmightbeintegers
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;
//obtainthecasesetting,ifthereisone
if(array_key_exists(Zend_Db::CASE_FOLDING,$options)){
$case=(int)$options[Zend_Db::CASE_FOLDING];
switch($case){
caseZend_Db::CASE_LOWER:
caseZend_Db::CASE_UPPER:
caseZend_Db::CASE_NATURAL:
$this->_caseFolding=$case;
break;
default:
/**@seeZend_Db_Adapter_Exception*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception('Casemustbeoneofthefollowingconstants:'
.'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]);
}
//obtainquotingpropertyifthereisone
if(array_key_exists(Zend_Db::AUTO_QUOTE_IDENTIFIERS,$options)){
$this->_autoQuoteIdentifiers=(bool)$options[Zend_Db::AUTO_QUOTE_IDENTIFIERS];
}
//obtainallowserializationpropertyifthereisone
if(array_key_exists(Zend_Db::ALLOW_SERIALIZATION,$options)){
$this->_allowSerialization=(bool)$options[Zend_Db::ALLOW_SERIALIZATION];
}
//obtainautoreconnectonunserializepropertyifthereisone
if(array_key_exists(Zend_Db::AUTO_RECONNECT_ON_UNSERIALIZE,$options)){
$this->_autoReconnectOnUnserialize=(bool)$options[Zend_Db::AUTO_RECONNECT_ON_UNSERIALIZE];
}
//createaprofilerobject
$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);
}
/**
*Checkforconfigoptionsthataremandatory.
*Throwexceptionsifanyaremissing.
*
*@paramarray$config
*@throwsZend_Db_Adapter_Exception
*/
protectedfunction_checkRequiredOptions(array$config)
{
//weneedatleastadbname
if(!array_key_exists('dbname',$config)){
/**@seeZend_Db_Adapter_Exception*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception("Configurationarraymusthaveakeyfor'dbname'thatnamesthedatabaseinstance");
}
if(!array_key_exists('password',$config)){
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception("Configurationarraymusthaveakeyfor'password'forlogincredentials");
}
if(!array_key_exists('username',$config)){
/**
*@seeZend_Db_Adapter_Exception
*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception("Configurationarraymusthaveakeyfor'username'forlogincredentials");
}
}
/**
*Returnstheunderlyingdatabaseconnectionobjectorresource.
*Ifnotpresentlyconnected,thisinitiatestheconnection.
*
*@returnobject|resource|null
*/
publicfunctiongetConnection()
{
$this->_connect();
return$this->_connection;
}
/**
*Returnstheconfigurationvariablesinthisadapter.
*
*@returnarray
*/
publicfunctiongetConfig()
{
return$this->_config;
}
/**
*Settheadapter'sprofilerobject.
*
*Theargumentmaybeaboolean,anassociativearray,aninstanceof
*Zend_Db_Profiler,oraninstanceofZend_Config.
*
*Abooleanargumentsetstheprofilertoenablediftrue,ordisabledif
*false.Theprofilerclassistheadapter'sdefaultprofilerclass,
*Zend_Db_Profiler.
*
*AninstanceofZend_Db_Profilersetstheadapter'sinstancetothat
*object.Theprofilerisenabledanddisabledseparately.
*
*Anassociativearrayargumentmaycontainanyofthekeys'enabled',
*'class',and'instance'.The'enabled'and'instance'keyscorrespondtothe
*booleanandobjecttypesdocumentedabove.The'class'keyisusedtonamea
*classtouseforacustomprofiler.TheclassmustbeZend_Db_Profilerora
*subclass.Theclassisinstantiatedwithnoconstructorarguments.The'class'
*optionisignoredwhenthe'instance'optionissupplied.
*
*AnobjectoftypeZend_Configmaycontaintheproperties'enabled','class',and
*'instance',justasifanassociativearrayhadbeenpassedinstead.
*
*@paramZend_Db_Profiler|Zend_Config|array|boolean$profiler
*@returnZend_Db_Adapter_AbstractProvidesafluentinterface
*@throwsZend_Db_Profiler_Exceptioniftheobjectinstanceorclassspecified
*isnotZend_Db_Profileroranextensionofthatclass.
*/
publicfunctionsetProfiler($profiler)
{
$enabled=null;
$profilerClass=$this->_defaultProfilerClass;
$profilerInstance=null;
if($profilerIsObject=is_object($profiler)){
if($profilerinstanceofZend_Db_Profiler){
$profilerInstance=$profiler;
}elseif($profilerinstanceofZend_Config){
$profiler=$profiler->toArray();
}else{
/**
*@seeZend_Db_Profiler_Exception
*/
require_once'Zend/Db/Profiler/Exception.php';
thrownewZend_Db_Profiler_Exception('ProfilerargumentmustbeaninstanceofeitherZend_Db_Profiler'
.'orZend_Configwhenprovidedasanobject');
}
}
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'];
}
}elseif(!$profilerIsObject){
$enabled=(bool)$profiler;
}
if($profilerInstance===null){
if(!class_exists($profilerClass)){
require_once'Zend/Loader.php';
Zend_Loader::loadClass($profilerClass);
}
$profilerInstance=new$profilerClass();
}
if(!$profilerInstanceinstanceofZend_Db_Profiler){
/**@seeZend_Db_Profiler_Exception*/
require_once'Zend/Db/Profiler/Exception.php';
thrownewZend_Db_Profiler_Exception('Class'.get_class($profilerInstance).'doesnotextend'
.'Zend_Db_Profiler');
}
if(null!==$enabled){
$profilerInstance->setEnabled($enabled);
}
$this->_profiler=$profilerInstance;
return$this;
}
/**
*Returnstheprofilerforthisadapter.
*
*@returnZend_Db_Profiler
*/
publicfunctiongetProfiler()
{
return$this->_profiler;
}
/**
*Getthedefaultstatementclass.
*
*@returnstring
*/
publicfunctiongetStatementClass()
{
return$this->_defaultStmtClass;
}
/**
*Setthedefaultstatementclass.
*
*@returnZend_Db_Adapter_AbstractFluentinterface
*/
publicfunctionsetStatementClass($class)
{
$this->_defaultStmtClass=$class;
return$this;
}
/**
*PreparesandexecutesanSQLstatementwithbounddata.
*
*@parammixed$sqlTheSQLstatementwithplaceholders.
*MaybeastringorZend_Db_Select.
*@parammixed$bindAnarrayofdatatobindtotheplaceholders.
*@returnZend_Db_Statement_Interface
*/
publicfunctionquery($sql,$bind=array())
{
//connecttothedatabaseifneeded
$this->_connect();
//isthe$sqlaZend_Db_Selectobject?
if($sqlinstanceofZend_Db_Select){
if(empty($bind)){
$bind=$sql->getBind();
}
$sql=$sql->assemble();
}
//makesure$bindtoanarray;
//don'tuse(array)typecastingbecause
//because$bindmaybeaZend_Db_Exprobject
if(!is_array($bind)){
$bind=array($bind);
}
//prepareandexecutethestatementwithprofiling
$stmt=$this->prepare($sql);
$stmt->execute($bind);
//returntheresultsembeddedinthepreparedstatementobject
$stmt->setFetchMode($this->_fetchMode);
return$stmt;
}
/**
*Leaveautocommitmodeandbeginatransaction.
*
*@returnZend_Db_Adapter_Abstract
*/
publicfunctionbeginTransaction()
{
$this->_connect();
$q=$this->_profiler->queryStart('begin',Zend_Db_Profiler::TRANSACTION);
$this->_beginTransaction();
$this->_profiler->queryEnd($q);
return$this;
}
/**
*Commitatransactionandreturntoautocommitmode.
*
*@returnZend_Db_Adapter_Abstract
*/
publicfunctioncommit()
{
$this->_connect();
$q=$this->_profiler->queryStart('commit',Zend_Db_Profiler::TRANSACTION);
$this->_commit();
$this->_profiler->queryEnd($q);
return$this;
}
/**
*Rollbackatransactionandreturntoautocommitmode.
*
*@returnZend_Db_Adapter_Abstract
*/
publicfunctionrollBack()
{
$this->_connect();
$q=$this->_profiler->queryStart('rollback',Zend_Db_Profiler::TRANSACTION);
$this->_rollBack();
$this->_profiler->queryEnd($q);
return$this;
}
/**
*Insertsatablerowwithspecifieddata.
*
*@parammixed$tableThetabletoinsertdatainto.
*@paramarray$bindColumn-valuepairs.
*@returnintThenumberofaffectedrows.
*@throwsZend_Db_Adapter_Exception
*/
publicfunctioninsert($table,array$bind)
{
//extractandquotecolnamesfromthearraykeys
$cols=array();
$vals=array();
$i=0;
foreach($bindas$col=>$val){
$cols[]=$this->quoteIdentifier($col,true);
if($valinstanceofZend_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{
/**@seeZend_Db_Adapter_Exception*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception(get_class($this)."doesn'tsupportpositionalornamedbinding");
}
}
}
}
//buildthestatement
$sql="INSERTINTO"
.$this->quoteIdentifier($table,true)
.'('.implode(',',$cols).')'
.'VALUES('.implode(',',$vals).')';
//executethestatementandreturnthenumberofaffectedrows
if($this->supportsParameters('positional')){
$bind=array_values($bind);
}
$stmt=$this->query($sql,$bind);
$result=$stmt->rowCount();
return$result;
}
/**
*UpdatestablerowswithspecifieddatabasedonaWHEREclause.
*
*@parammixed$tableThetabletoupdate.
*@paramarray$bindColumn-valuepairs.
*@parammixed$whereUPDATEWHEREclause(s).
*@returnintThenumberofaffectedrows.
*@throwsZend_Db_Adapter_Exception
*/
publicfunctionupdate($table,array$bind,$where='')
{
/**
*Build"col=?"pairsforthestatement,
*exceptforZend_Db_Exprwhichistreatedliterally.
*/
$set=array();
$i=0;
foreach($bindas$col=>$val){
if($valinstanceofZend_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{
/**@seeZend_Db_Adapter_Exception*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception(get_class($this)."doesn'tsupportpositionalornamedbinding");
}
}
}
$set[]=$this->quoteIdentifier($col,true).'='.$val;
}
$where=$this->_whereExpr($where);
/**
*BuildtheUPDATEstatement
*/
$sql="UPDATE"
.$this->quoteIdentifier($table,true)
.'SET'.implode(',',$set)
.(($where)?"WHERE$where":'');
/**
*Executethestatementandreturnthenumberofaffectedrows
*/
if($this->supportsParameters('positional')){
$stmt=$this->query($sql,array_values($bind));
}else{
$stmt=$this->query($sql,$bind);
}
$result=$stmt->rowCount();
return$result;
}
/**
*DeletestablerowsbasedonaWHEREclause.
*
*@parammixed$tableThetabletoupdate.
*@parammixed$whereDELETEWHEREclause(s).
*@returnintThenumberofaffectedrows.
*/
publicfunctiondelete($table,$where='')
{
$where=$this->_whereExpr($where);
/**
*BuildtheDELETEstatement
*/
$sql="DELETEFROM"
.$this->quoteIdentifier($table,true)
.(($where)?"WHERE$where":'');
/**
*Executethestatementandreturnthenumberofaffectedrows
*/
$stmt=$this->query($sql);
$result=$stmt->rowCount();
return$result;
}
/**
*Convertanarray,string,orZend_Db_Exprobject
*intoastringtoputinaWHEREclause.
*
*@parammixed$where
*@returnstring
*/
protectedfunction_whereExpr($where)
{
if(empty($where)){
return$where;
}
if(!is_array($where)){
$where=array($where);
}
foreach($whereas$cond=>&$term){
//is$condanint?(i.e.Notacondition)
if(is_int($cond)){
//$termisthefullcondition
if($terminstanceofZend_Db_Expr){
$term=$term->__toString();
}
}else{
//$condistheconditionwithplaceholder,
//and$termisquotedintothecondition
$term=$this->quoteInto($cond,$term);
}
$term='('.$term.')';
}
$where=implode('AND',$where);
return$where;
}
/**
*CreatesandreturnsanewZend_Db_Selectobjectforthisadapter.
*
*@returnZend_Db_Select
*/
publicfunctionselect()
{
returnnewZend_Db_Select($this);
}
/**
*Getthefetchmode.
*
*@returnint
*/
publicfunctiongetFetchMode()
{
return$this->_fetchMode;
}
/**
*FetchesallSQLresultrowsasasequentialarray.
*UsesthecurrentfetchModefortheadapter.
*
*@paramstring|Zend_Db_Select$sqlAnSQLSELECTstatement.
*@parammixed$bindDatatobindintoSELECTplaceholders.
*@parammixed$fetchModeOverridecurrentfetchmode.
*@returnarray
*/
publicfunctionfetchAll($sql,$bind=array(),$fetchMode=null)
{
if($fetchMode===null){
$fetchMode=$this->_fetchMode;
}
$stmt=$this->query($sql,$bind);
$result=$stmt->fetchAll($fetchMode);
return$result;
}
/**
*FetchesthefirstrowoftheSQLresult.
*UsesthecurrentfetchModefortheadapter.
*
*@paramstring|Zend_Db_Select$sqlAnSQLSELECTstatement.
*@parammixed$bindDatatobindintoSELECTplaceholders.
*@parammixed$fetchModeOverridecurrentfetchmode.
*@returnmixedArray,object,orscalardependingonfetchmode.
*/
publicfunctionfetchRow($sql,$bind=array(),$fetchMode=null)
{
if($fetchMode===null){
$fetchMode=$this->_fetchMode;
}
$stmt=$this->query($sql,$bind);
$result=$stmt->fetch($fetchMode);
return$result;
}
/**
*FetchesallSQLresultrowsasanassociativearray.
*
*Thefirstcolumnisthekey,theentirerowarrayisthe
*value.Youshouldconstructthequerytobesurethat
*thefirstcolumncontainsuniquevalues,orelse
*rowswithduplicatevaluesinthefirstcolumnwill
*overwritepreviousdata.
*
*@paramstring|Zend_Db_Select$sqlAnSQLSELECTstatement.
*@parammixed$bindDatatobindintoSELECTplaceholders.
*@returnarray
*/
publicfunctionfetchAssoc($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;
}
/**
*FetchesthefirstcolumnofallSQLresultrowsasanarray.
*
*@paramstring|Zend_Db_Select$sqlAnSQLSELECTstatement.
*@parammixed$bindDatatobindintoSELECTplaceholders.
*@returnarray
*/
publicfunctionfetchCol($sql,$bind=array())
{
$stmt=$this->query($sql,$bind);
$result=$stmt->fetchAll(Zend_Db::FETCH_COLUMN,0);
return$result;
}
/**
*FetchesallSQLresultrowsasanarrayofkey-valuepairs.
*
*Thefirstcolumnisthekey,thesecondcolumnisthe
*value.
*
*@paramstring|Zend_Db_Select$sqlAnSQLSELECTstatement.
*@parammixed$bindDatatobindintoSELECTplaceholders.
*@returnarray
*/
publicfunctionfetchPairs($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;
}
/**
*FetchesthefirstcolumnofthefirstrowoftheSQLresult.
*
*@paramstring|Zend_Db_Select$sqlAnSQLSELECTstatement.
*@parammixed$bindDatatobindintoSELECTplaceholders.
*@returnstring
*/
publicfunctionfetchOne($sql,$bind=array())
{
$stmt=$this->query($sql,$bind);
$result=$stmt->fetchColumn(0);
return$result;
}
/**
*Quotearawstring.
*
*@paramstring$valueRawstring
*@returnstringQuotedstring
*/
protectedfunction_quote($value)
{
if(is_int($value)){
return$value;
}elseif(is_float($value)){
returnsprintf('%F',$value);
}
return"'".addcslashes($value,"\000\n\r\\'\"\032")."'";
}
/**
*SafelyquotesavalueforanSQLstatement.
*
*Ifanarrayispassedasthevalue,thearrayvaluesarequoted
*andthenreturnedasacomma-separatedstring.
*
*@parammixed$valueThevaluetoquote.
*@parammixed$typeOPTIONALtheSQLdatatypename,orconstant,ornull.
*@returnmixedAnSQL-safequotedvalue(orstringofseparatedvalues).
*/
publicfunctionquote($value,$type=null)
{
$this->_connect();
if($valueinstanceofZend_Db_Select){
return'('.$value->assemble().')';
}
if($valueinstanceofZend_Db_Expr){
return$value->__toString();
}
if(is_array($value)){
foreach($valueas&$val){
$val=$this->quote($val,$type);
}
returnimplode(',',$value);
}
if($type!==null&&array_key_exists($type=strtoupper($type),$this->_numericDataTypes)){
$quotedValue='0';
switch($this->_numericDataTypes[$type]){
caseZend_Db::INT_TYPE://32-bitinteger
$quotedValue=(string)intval($value);
break;
caseZend_Db::BIGINT_TYPE://64-bitinteger
//ANSISQL-stylehexliterals(e.g.x'[\dA-F]+')
//arenotsupportedhere,becausethesearestring
//literals,notnumericliterals.
if(preg_match('/^(
[+-]?#optionalsign
(?:
0[Xx][\da-fA-F]+#ODBC-stylehexadecimal
|\d+#decimaloroctal,orMySQLZEROFILLdecimal
(?:[eE][+-]?\d+)?#optionalexponentondecimalsoroctals
)
)/x',
(string)$value,$matches)){
$quotedValue=$matches[1];
}
break;
caseZend_Db::FLOAT_TYPE://floatordecimal
$quotedValue=sprintf('%F',$value);
}
return$quotedValue;
}
return$this->_quote($value);
}
/**
*Quotesavalueandplacesintoapieceoftextataplaceholder.
*
*Theplaceholderisaquestion-mark;allplaceholderswillbereplaced
*withthequotedvalue.Forexample:
*
*<code>
*$text="WHEREdate<?";
*$date="2005-01-02";
*$safe=$sql->quoteInto($text,$date);
*//$safe="WHEREdate<'2005-01-02'"
*</code>
*
*@paramstring$textThetextwithaplaceholder.
*@parammixed$valueThevaluetoquote.
*@paramstring$typeOPTIONALSQLdatatype
*@paraminteger$countOPTIONALcountofplaceholderstoreplace
*@returnstringAnSQL-safequotedvalueplacedintotheoriginaltext.
*/
publicfunctionquoteInto($text,$value,$type=null,$count=null)
{
if($count===null){
returnstr_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;
}
}
/**
*Quotesanidentifier.
*
*Acceptsastringrepresentingaqualifiedindentifier.ForExample:
*<code>
*$adapter->quoteIdentifier('myschema.mytable')
*</code>
*Returns:"myschema"."mytable"
*
*Or,anarrayofoneormoreidentifiersthatmayformaqualifiedidentifier:
*<code>
*$adapter->quoteIdentifier(array('myschema','my.table'))
*</code>
*Returns:"myschema"."my.table"
*
*Theactualquotecharactersurroundingtheidentifiersmayvarydependingon
*theadapter.
*
*@paramstring|array|Zend_Db_Expr$identTheidentifier.
*@paramboolean$autoIftrue,heedtheAUTO_QUOTE_IDENTIFIERSconfigoption.
*@returnstringThequotedidentifier.
*/
publicfunctionquoteIdentifier($ident,$auto=false)
{
return$this->_quoteIdentifierAs($ident,null,$auto);
}
/**
*Quoteacolumnidentifierandalias.
*
*@paramstring|array|Zend_Db_Expr$identTheidentifierorexpression.
*@paramstring$aliasAnaliasforthecolumn.
*@paramboolean$autoIftrue,heedtheAUTO_QUOTE_IDENTIFIERSconfigoption.
*@returnstringThequotedidentifierandalias.
*/
publicfunctionquoteColumnAs($ident,$alias,$auto=false)
{
return$this->_quoteIdentifierAs($ident,$alias,$auto);
}
/**
*Quoteatableidentifierandalias.
*
*@paramstring|array|Zend_Db_Expr$identTheidentifierorexpression.
*@paramstring$aliasAnaliasforthetable.
*@paramboolean$autoIftrue,heedtheAUTO_QUOTE_IDENTIFIERSconfigoption.
*@returnstringThequotedidentifierandalias.
*/
publicfunctionquoteTableAs($ident,$alias=null,$auto=false)
{
return$this->_quoteIdentifierAs($ident,$alias,$auto);
}
/**
*Quoteanidentifierandanoptionalalias.
*
*@paramstring|array|Zend_Db_Expr$identTheidentifierorexpression.
*@paramstring$aliasAnoptionalalias.
*@paramboolean$autoIftrue,heedtheAUTO_QUOTE_IDENTIFIERSconfigoption.
*@paramstring$asThestringtoaddbetweentheidentifier/expressionandthealias.
*@returnstringThequotedidentifierandalias.
*/
protectedfunction_quoteIdentifierAs($ident,$alias=null,$auto=false,$as='AS')
{
if($identinstanceofZend_Db_Expr){
$quoted=$ident->__toString();
}elseif($identinstanceofZend_Db_Select){
$quoted='('.$ident->assemble().')';
}else{
if(is_string($ident)){
$ident=explode('.',$ident);
}
if(is_array($ident)){
$segments=array();
foreach($identas$segment){
if($segmentinstanceofZend_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;
}
/**
*Quoteanidentifier.
*
*@paramstring$valueTheidentifierorexpression.
*@paramboolean$autoIftrue,heedtheAUTO_QUOTE_IDENTIFIERSconfigoption.
*@returnstringThequotedidentifierandalias.
*/
protectedfunction_quoteIdentifier($value,$auto=false)
{
if($auto===false||$this->_autoQuoteIdentifiers===true){
$q=$this->getQuoteIdentifierSymbol();
return($q.str_replace("$q","$q$q",$value).$q);
}
return$value;
}
/**
*Returnsthesymboltheadapterusesfordelimitedidentifiers.
*
*@returnstring
*/
publicfunctiongetQuoteIdentifierSymbol()
{
return'"';
}
/**
*Returnthemostrecentvaluefromthespecifiedsequenceinthedatabase.
*ThisissupportedonlyonRDBMSbrandsthatsupportsequences
*(e.g.Oracle,PostgreSQL,DB2).OtherRDBMSbrandsreturnnull.
*
*@paramstring$sequenceName
*@returnstring
*/
publicfunctionlastSequenceId($sequenceName)
{
returnnull;
}
/**
*Generateanewvaluefromthespecifiedsequenceinthedatabase,andreturnit.
*ThisissupportedonlyonRDBMSbrandsthatsupportsequences
*(e.g.Oracle,PostgreSQL,DB2).OtherRDBMSbrandsreturnnull.
*
*@paramstring$sequenceName
*@returnstring
*/
publicfunctionnextSequenceId($sequenceName)
{
returnnull;
}
/**
*Helpermethodtochangethecaseofthestringsused
*whenreturningresultsetsinFETCH_ASSOCandFETCH_BOTH
*modes.
*
*Thisisnotintendedtobeusedbyapplicationcode,
*butthemethodmustbepublicsotheStatementclass
*caninvokeit.
*
*@paramstring$key
*@returnstring
*/
publicfunctionfoldCase($key)
{
switch($this->_caseFolding){
caseZend_Db::CASE_LOWER:
$value=strtolower((string)$key);
break;
caseZend_Db::CASE_UPPER:
$value=strtoupper((string)$key);
break;
caseZend_Db::CASE_NATURAL:
default:
$value=(string)$key;
}
return$value;
}
/**
*calledwhenobjectisgettingserialized
*ThisdisconnectstheDBobjectthatcantbeserialized
*
*@throwsZend_Db_Adapter_Exception
*@returnarray
*/
publicfunction__sleep()
{
if($this->_allowSerialization==false){
/**@seeZend_Db_Adapter_Exception*/
require_once'Zend/Db/Adapter/Exception.php';
thrownewZend_Db_Adapter_Exception(get_class($this)."isnotallowedtobeserialized");
}
$this->_connection=false;
returnarray_keys(array_diff_key(get_object_vars($this),array('_connection'=>false)));
}
/**
*calledwhenobjectisgettingunserialized
*
*@returnvoid
*/
publicfunction__wakeup()
{
if($this->_autoReconnectOnUnserialize==true){
$this->getConnection();
}
}
/**
*AbstractMethods
*/
/**
*Returnsalistofthetablesinthedatabase.
*
*@returnarray
*/
abstractpublicfunctionlistTables();
/**
*Returnsthecolumndescriptionsforatable.
*
*Thereturnvalueisanassociativearraykeyedbythecolumnname,
*asreturnedbytheRDBMS.
*
*Thevalueofeacharrayelementisanassociativearray
*withthefollowingkeys:
*
*SCHEMA_NAME=>string;nameofdatabaseorschema
*TABLE_NAME=>string;
*COLUMN_NAME=>string;columnname
*COLUMN_POSITION=>number;ordinalpositionofcolumnintable
*DATA_TYPE=>string;SQLdatatypenameofcolumn
*DEFAULT=>string;defaultexpressionofcolumn,nullifnone
*NULLABLE=>boolean;trueifcolumncanhavenulls
*LENGTH=>number;lengthofCHAR/VARCHAR
*SCALE=>number;scaleofNUMERIC/DECIMAL
*PRECISION=>number;precisionofNUMERIC/DECIMAL
*UNSIGNED=>boolean;unsignedpropertyofanintegertype
*PRIMARY=>boolean;trueifcolumnispartoftheprimarykey
*PRIMARY_POSITION=>integer;positionofcolumninprimarykey
*
*@paramstring$tableName
*@paramstring$schemaNameOPTIONAL
*@returnarray
*/
abstractpublicfunctiondescribeTable($tableName,$schemaName=null);
/**
*Createsaconnectiontothedatabase.
*
*@returnvoid
*/
abstractprotectedfunction_connect();
/**
*Testifaconnectionisactive
*
*@returnboolean
*/
abstractpublicfunctionisConnected();
/**
*Forcetheconnectiontoclose.
*
*@returnvoid
*/
abstractpublicfunctioncloseConnection();
/**
*PrepareastatementandreturnaPDOStatement-likeobject.
*
*@paramstring|Zend_Db_Select$sqlSQLquery
*@returnZend_Db_Statement|PDOStatement
*/
abstractpublicfunctionprepare($sql);
/**
*GetsthelastIDgeneratedautomaticallybyanIDENTITY/AUTOINCREMENTcolumn.
*
*Asaconvention,onRDBMSbrandsthatsupportsequences
*(e.g.Oracle,PostgreSQL,DB2),thismethodformsthenameofasequence
*fromtheargumentsandreturnsthelastidgeneratedbythatsequence.
*OnRDBMSbrandsthatsupportIDENTITY/AUTOINCREMENTcolumns,thismethod
*returnsthelastvaluegeneratedforsuchacolumn,andthetablename
*argumentisdisregarded.
*
*@paramstring$tableNameOPTIONALNameoftable.
*@paramstring$primaryKeyOPTIONALNameofprimarykeycolumn.
*@returnstring
*/
abstractpublicfunctionlastInsertId($tableName=null,$primaryKey=null);
/**
*Beginatransaction.
*/
abstractprotectedfunction_beginTransaction();
/**
*Commitatransaction.
*/
abstractprotectedfunction_commit();
/**
*Roll-backatransaction.
*/
abstractprotectedfunction_rollBack();
/**
*Setthefetchmode.
*
*@paraminteger$mode
*@returnvoid
*@throwsZend_Db_Adapter_Exception
*/
abstractpublicfunctionsetFetchMode($mode);
/**
*Addsanadapter-specificLIMITclausetotheSELECTstatement.
*
*@parammixed$sql
*@paraminteger$count
*@paraminteger$offset
*@returnstring
*/
abstractpublicfunctionlimit($sql,$count,$offset=0);
/**
*CheckiftheadaptersupportsrealSQLparameters.
*
*@paramstring$type'positional'or'named'
*@returnbool
*/
abstractpublicfunctionsupportsParameters($type);
/**
*RetrieveserverversioninPHPstyle
*
*@returnstring
*/
abstractpublicfunctiongetServerVersion();
}
到此,我已经晕了。你呢???
哈哈哈。。。
下面看一些简单的案例
插入数据到数据库:
<?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$tablewhereid=$last_insert_id";
$result=$db->fetchRow($sql);
echo"<p>";
foreach($resultas$key=>$val){
echo$key;
echo"值为:";
echo$val;
echo"<p>";
}
}else{
echo"