Zend_Db_Adapter.xml 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- EN-Revision: 19173 -->
  3. <!-- Reviewed: no -->
  4. <sect1 id="zend.db.adapter">
  5. <title>Zend_Db_Adapter</title>
  6. <para>
  7. <classname>Zend_Db</classname> y sus clases relacionadas proporcionan una interfaz
  8. simple de base de datos <acronym>SQL</acronym> para Zend Framework. El
  9. <classname>Zend_Db_Adapter</classname> es la clase base que se utiliza para conectar su
  10. aplicación <acronym>PHP</acronym> A una base de datos (<acronym>RDBMS</acronym>). Existen diferentes
  11. clases Adapters(Adaptador) para cada tipo de base de datos
  12. (<acronym>RDBMS</acronym>).
  13. </para>
  14. <para>
  15. Las clases
  16. <methodname>Adapters</methodname>
  17. de <classname>Zend_Db</classname> crean un puente entre las extensiones de base de
  18. datos de <acronym>PHP</acronym> hacia una interfaz común, para ayudarle a escribir
  19. aplicaciones <acronym>PHP</acronym> una sola vez y poder desplegar múltiples
  20. tipos de base de datos (<acronym>RDBMS</acronym>) con muy poco esfuerzo.
  21. </para>
  22. <para>
  23. La Interfaz de la clase adaptador (adapter) es similar a la
  24. intefaz de la extensión
  25. <ulink url="http://www.php.net/pdo">PHP Data Objects</ulink>
  26. . <classname>Zend_Db</classname> proporciona clases Adaptadoras para los drivers <acronym>PDO</acronym> de
  27. los siguientes tipos de <acronym>RDBMS</acronym>:
  28. </para>
  29. <itemizedlist>
  30. <listitem>
  31. <para>
  32. IBM DB2 e Informix Dynamic Server (IDS), usando la
  33. extensión <acronym>PHP</acronym>
  34. <ulink url="http://www.php.net/pdo-ibm">pdo_ibm</ulink>
  35. </para>
  36. </listitem>
  37. <listitem>
  38. <para>
  39. MySQL, usando la extensión <acronym>PHP</acronym>
  40. <ulink url="http://www.php.net/pdo-mysql">
  41. pdo_mysql
  42. </ulink>
  43. </para>
  44. </listitem>
  45. <listitem>
  46. <para>
  47. Microsoft SQL Server, usando la extensión <acronym>PHP</acronym>
  48. <ulink url="http://www.php.net/pdo-mssql">
  49. pdo_mssql
  50. </ulink>
  51. </para>
  52. </listitem>
  53. <listitem>
  54. <para>
  55. Oracle, usando la extensión <acronym>PHP</acronym>
  56. <ulink url="http://www.php.net/pdo-oci">pdo_oci</ulink>
  57. </para>
  58. </listitem>
  59. <listitem>
  60. <para>
  61. PostgreSQL, usando la extensión <acronym>PHP</acronym>
  62. <ulink url="http://www.php.net/pdo-pgsql">
  63. pdo_pgsql
  64. </ulink>
  65. </para>
  66. </listitem>
  67. <listitem>
  68. <para>
  69. SQLite, usando la extensión <acronym>PHP</acronym>
  70. <ulink url="http://www.php.net/pdo-sqlite">
  71. pdo_sqlite
  72. </ulink>
  73. </para>
  74. </listitem>
  75. </itemizedlist>
  76. <para>
  77. Ademas, <classname>Zend_Db</classname> proporciona clases Adaptadoras que utilizan las
  78. extensiones de base de datos de <acronym>PHP</acronym> de los siguientes tipos:
  79. </para>
  80. <itemizedlist>
  81. <listitem>
  82. <para>
  83. MySQL, usando la extensión <acronym>PHP</acronym>
  84. <ulink url="http://www.php.net/mysqli">mysqli</ulink>
  85. </para>
  86. </listitem>
  87. <listitem>
  88. <para>
  89. Oracle, usando la extensión <acronym>PHP</acronym>
  90. <ulink url="http://www.php.net/oci8">oci8</ulink>
  91. </para>
  92. </listitem>
  93. <listitem>
  94. <para>
  95. IBM DB2, usando la extensión <acronym>PHP</acronym>
  96. <ulink url="http://www.php.net/ibm_db2">ibm_db2</ulink>
  97. </para>
  98. </listitem>
  99. <listitem>
  100. <para>
  101. Firebird/Interbase, usando la extensión <acronym>PHP</acronym>
  102. <ulink url="http://www.php.net/ibase">
  103. php_interbase
  104. </ulink>
  105. </para>
  106. </listitem>
  107. </itemizedlist>
  108. <note>
  109. <para>
  110. Cada Zend_Db_Adaptador utiliza una extensión <acronym>PHP</acronym>. Se debe de
  111. tener habilitada la respectiva extensión en su entorno <acronym>PHP</acronym>
  112. para utilizar un <classname>Zend_Db_Adapter</classname>. Por ejemplo, si se utiliza
  113. una clase <classname>Zend_Db_Adapter</classname> basada en <acronym>PDO</acronym> , tiene que
  114. habilitar tanto la extensión <acronym>PDO</acronym> como el driver <acronym>PDO</acronym> del tipo
  115. de base de datos que se utiliza.
  116. </para>
  117. </note>
  118. <sect2 id="zend.db.adapter.connecting">
  119. <title>
  120. Conexión a una Base de Datos utilizando un Adaptador
  121. </title>
  122. <para>
  123. Esta sección describe cómo crear una instancia de un
  124. Adaptador de base de datos. Esto corresponde a establecer
  125. una conexión a un servidor de Base de Datos (<acronym>RDBMS</acronym>) desde su
  126. aplicación <acronym>PHP</acronym>.
  127. </para>
  128. <sect3 id="zend.db.adapter.connecting.constructor">
  129. <title>Usando un Constructor de Zend_Db Adapter</title>
  130. <para>
  131. Se puede crear una instancia de un Adaptador utilizando
  132. su constructor. Un constructor de adaptador toma un
  133. argumento, que es un conjunto de parámetros utilizados
  134. para declarar la conexión.
  135. </para>
  136. <example id="zend.db.adapter.connecting.constructor.example">
  137. <title>Usando el Constructor de un Adaptador</title>
  138. <programlisting language="php"><![CDATA[
  139. $db = new Zend_Db_Adapter_Pdo_Mysql(array(
  140. 'host' => '127.0.0.1',
  141. 'username' => 'webuser',
  142. 'password' => 'xxxxxxxx',
  143. 'dbname' => 'test'
  144. ));
  145. ]]></programlisting>
  146. </example>
  147. </sect3>
  148. <sect3 id="zend.db.adapter.connecting.factory">
  149. <title>Usando el Zend_Db Factory</title>
  150. <para>
  151. Como alternativa a la utilización directa del
  152. constructor de un adaptador, se puede crear una
  153. instancia del adaptador que use el método estático
  154. <methodname>Zend_Db::factory()</methodname>
  155. . Este método carga dinámicamente el archivo de clase
  156. Adaptador bajo demanda, usando
  157. <link linkend="zend.loader.load.class">
  158. Zend_Loader::loadClass()
  159. </link>
  160. .
  161. </para>
  162. <para>
  163. El primer argumento es una cadena que nombra al nombre base
  164. de la clase Adaptador. Por ejemplo, la cadena
  165. '<classname>Pdo_Mysql</classname>' corresponde a la clase
  166. <classname>Zend_Db_Adapter_Pdo_Mysql</classname>. El segundo argumento es el
  167. mismo array de parámetros que hubiera enviado al
  168. constructor del adaptador.
  169. </para>
  170. <example id="zend.db.adapter.connecting.factory.example">
  171. <title>Usando el Adaptador del método factory</title>
  172. <programlisting language="php"><![CDATA[
  173. // No necesitamos la siguiente declaración, porque
  174. // el archivo Zend_Db_Adapter_Pdo_Mysql será cargado para nosotros por el método
  175. // factory de Zend_Db.
  176. // require_once 'Zend/Db/Adapter/Pdo/Mysql.php';
  177. // carga automaticamente la clase Zend_Db_Adapter_Pdo_Mysql
  178. // y crea una instancia de la misma
  179. $db = Zend_Db::factory('Pdo_Mysql', array(
  180. 'host' => '127.0.0.1',
  181. 'username' => 'webuser',
  182. 'password' => 'xxxxxxxx',
  183. 'dbname' => 'test'
  184. ));
  185. ]]></programlisting>
  186. </example>
  187. <para>
  188. Si crea su propia clase que extiende a
  189. <classname>Zend_Db_Adapter_Abstract</classname>, pero no nombra su clase con el prefijo
  190. de paquete "<classname>Zend_Db_Adapter</classname>", se puede utilizar el método
  191. <methodname>factory()</methodname>
  192. para cargar su adaptador si se especifica la parte principal
  193. de la clase del adaptador con la clave "adapterNamespace" en
  194. el conjunto de parámetros
  195. </para>
  196. <example id="zend.db.adapter.connecting.factory.example2">
  197. <title>
  198. Usando el método factory para una clase Adaptador
  199. personalizada
  200. </title>
  201. <programlisting language="php"><![CDATA[
  202. // No tenemos que cargar el archivo de clase Adaptador
  203. // porque será cargado para nosotros por el método factory de Zend_Db.
  204. // Automáticamente carga la clase MyProject_Db_Adapter_Pdo_Mysql
  205. // y crea una instancia de ella.
  206. $db = Zend_Db::factory('Pdo_Mysql', array(
  207. 'host' => '127.0.0.1',
  208. 'username' => 'webuser',
  209. 'password' => 'xxxxxxxx',
  210. 'dbname' => 'test',
  211. 'adapterNamespace' => 'MyProject_Db_Adapter'
  212. ));
  213. ]]></programlisting>
  214. </example>
  215. </sect3>
  216. <sect3 id="zend.db.adapter.connecting.factory-config">
  217. <title>Uso de Zend_Config con Zend_Db Factory</title>
  218. <para>
  219. Opcionalmente, se puede especificar cualquier
  220. argumento del método
  221. <methodname>factory()</methodname>
  222. como un objeto de tipo
  223. <link linkend="zend.config">Zend_Config</link>
  224. .
  225. </para>
  226. <para>
  227. Si el primer argumento es un objeto de configuración, se
  228. espera que contenga una propiedad llamada
  229. <property>adapter</property>
  230. , conteniendo la cadena que da nombre al nombre base de la
  231. clase de adaptador. Opcionalmente, el objeto puede
  232. contener una propiedad llamada
  233. <property>params</property>
  234. , con subpropiedades correspondientes a nombres de parámetros
  235. del adaptador. Esto es usado sólo si el segundo
  236. argumento del método <methodname>factory()</methodname> se ha omitido.
  237. </para>
  238. <example id="zend.db.adapter.connecting.factory.example1">
  239. <title>
  240. Uso del método factory del Adaptador con un objeto Zend_Config
  241. </title>
  242. <para>
  243. En el siguiente ejemplo, un objeto <classname>Zend_Config</classname> es
  244. creado usando un array. También puedes cargar los datos de
  245. un archivo externo, por ejemplo con
  246. <link linkend="zend.config.adapters.ini">
  247. Zend_Config_Ini
  248. </link>
  249. o
  250. <link linkend="zend.config.adapters.xml">
  251. Zend_Config_Xml
  252. </link>
  253. .
  254. </para>
  255. <programlisting language="php"><![CDATA[
  256. $config = new Zend_Config(
  257. array(
  258. 'database' => array(
  259. 'adapter' => 'Mysqli',
  260. 'params' => array(
  261. 'dbname' => 'test',
  262. 'username' => 'webuser',
  263. 'password' => 'secret',
  264. )
  265. )
  266. )
  267. );
  268. $db = Zend_Db::factory($config->database);
  269. ]]></programlisting>
  270. </example>
  271. <para>
  272. El segundo argumento del método
  273. <methodname>factory()</methodname>
  274. puede ser un array asociativo con entradas
  275. correspondientes a los parámetros del adaptador. Este argumento es
  276. opcional. Si el primer argumento es de tipo <classname>Zend_Config</classname>,
  277. se asume que tiene todos los parametros, y el segundo
  278. argumento es ignorado.
  279. </para>
  280. </sect3>
  281. <sect3 id="zend.db.adapter.connecting.parameters">
  282. <title>Parámetros del Adaptador</title>
  283. <para>
  284. El siguiente listado explica parámetros comunes reconocidos por
  285. Adaptador de clases <classname>Zend_Db</classname>.
  286. </para>
  287. <itemizedlist>
  288. <listitem>
  289. <para>
  290. <emphasis>host</emphasis>
  291. : una string conteniendo un nombre de host o dirección IP
  292. del servidor de base de datos. Si la base de datos está corriendo
  293. sobre el mismo host que la aplicación <acronym>PHP</acronym>,
  294. usted puede utilizar 'localhost' o '127.0.0.1'.
  295. </para>
  296. </listitem>
  297. <listitem>
  298. <para>
  299. <emphasis>username</emphasis>
  300. : identificador de cuenta para autenticar una conexión al
  301. servidor <acronym>RDBMS</acronym>.
  302. </para>
  303. </listitem>
  304. <listitem>
  305. <para>
  306. <emphasis>password</emphasis>
  307. : la contraseña de la cuenta para la autenticación de credenciales
  308. de conexión con el servidor <acronym>RDBMS</acronym>
  309. </para>
  310. </listitem>
  311. <listitem>
  312. <para>
  313. <emphasis>dbname</emphasis>
  314. : nombre de la base de datos en el servidor <acronym>RDBMS</acronym>.
  315. </para>
  316. </listitem>
  317. <listitem>
  318. <para>
  319. <emphasis>port</emphasis>
  320. : algunos servidores <acronym>RDBMS</acronym> pueden aceptar conexiones de red
  321. sobre un número de puerto específico.
  322. El parámetro del puerto le permite especificar el puerto al
  323. que su aplicación <acronym>PHP</acronym> se conecta, para que concuerde el puerto
  324. configurado en el servidor <acronym>RDBMS</acronym>.
  325. </para>
  326. </listitem>
  327. <listitem>
  328. <para>
  329. <emphasis>charset</emphasis>:
  330. specify the charset used for the connection.
  331. </para>
  332. </listitem>
  333. <listitem>
  334. <para>
  335. <emphasis>options</emphasis>:
  336. : este parámetro es un array asociativo de
  337. opciones que son genéricas a todas las clases <classname>Zend_Db_Adapter</classname>.
  338. </para>
  339. </listitem>
  340. <listitem>
  341. <para>
  342. <emphasis>
  343. driver_options
  344. </emphasis>
  345. : este parámetro es un array asociativo de opciones adicionales
  346. para una extensión de base de datos dada.
  347. un uso típico de este parámetro es establecer atributos
  348. de un driver <acronym>PDO</acronym>.
  349. </para>
  350. </listitem>
  351. <listitem>
  352. <para>
  353. <emphasis>
  354. adapterNamespace
  355. </emphasis>
  356. : nombre de la parte inicial del nombre de las clase para el
  357. adaptador, en lugar de '<classname>Zend_Db_Adapter</classname>'. Utilice
  358. esto si usted necesita usar el método
  359. <methodname>factory()</methodname>
  360. para cargar un adaptador de clase de base de datos que no sea
  361. de Zend.
  362. </para>
  363. </listitem>
  364. </itemizedlist>
  365. <example id="zend.db.adapter.connecting.parameters.example1">
  366. <title>
  367. Passing the case-folding option to the factory
  368. </title>
  369. <para>
  370. Usted puede pasar esta opción específica por la constante
  371. <classname>Zend_Db::CASE_FOLDING</classname>
  372. . Este corresponde al atributo
  373. <constant>ATTR_CASE</constant>
  374. en los drivers de base de datos <acronym>PDO</acronym> e IBM DB2,
  375. ajustando la sensibilidad de las claves tipo cadena en los resultados
  376. de consultas. La opción toma los valores
  377. <classname>Zend_Db::CASE_NATURAL</classname>
  378. (el predeterminado),
  379. <classname>Zend_Db::CASE_UPPER</classname>
  380. , y
  381. <classname>Zend_Db::CASE_LOWER</classname>
  382. .
  383. </para>
  384. <programlisting language="php"><![CDATA[
  385. $options = array(
  386. Zend_Db::CASE_FOLDING => Zend_Db::CASE_UPPER
  387. );
  388. $params = array(
  389. 'host' => '127.0.0.1',
  390. 'username' => 'webuser',
  391. 'password' => 'xxxxxxxx',
  392. 'dbname' => 'test',
  393. 'options' => $options
  394. );
  395. $db = Zend_Db::factory('Db2', $params);
  396. ]]></programlisting>
  397. </example>
  398. <example id="zend.db.adapter.connecting.parameters.example2">
  399. <title>
  400. Passing the auto-quoting option to the factory
  401. </title>
  402. <para>
  403. Usted puede especificar esta opción por la constante
  404. <methodname>Zend_Db::AUTO_QUOTE_IDENTIFIERS</methodname>
  405. . Si el valor es
  406. <constant>TRUE</constant>
  407. (el predeterminado), los identificadores como nombres de tabla,
  408. nombres de columna, e incluso los alias son delimitados en la
  409. sintaxis <acronym>SQL</acronym>generada por el Adatador del objeto.
  410. Esto hace que sea sencillo utilizar identificadores que contengan
  411. palabras reservadas de <acronym>SQL</acronym>, o caracteres especiales. Si el valor es
  412. <constant>FALSE</constant>
  413. , los identificadores no son delimitados automáticamente. Si
  414. usted necesita delimitar identificadores, debe hacer usted mismo
  415. utilizando el método
  416. <methodname>quoteIdentifier()</methodname>
  417. .
  418. </para>
  419. <programlisting language="php"><![CDATA[
  420. $options = array(
  421. Zend_Db::AUTO_QUOTE_IDENTIFIERS => false
  422. );
  423. $params = array(
  424. 'host' => '127.0.0.1',
  425. 'username' => 'webuser',
  426. 'password' => 'xxxxxxxx',
  427. 'dbname' => 'test',
  428. 'options' => $options
  429. );
  430. $db = Zend_Db::factory('Pdo_Mysql', $params);
  431. ]]></programlisting>
  432. </example>
  433. <example id="zend.db.adapter.connecting.parameters.example3">
  434. <title>Passing PDO driver options to the factory</title>
  435. <programlisting language="php"><![CDATA[
  436. $pdoParams = array(
  437. PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
  438. );
  439. $params = array(
  440. 'host' => '127.0.0.1',
  441. 'username' => 'webuser',
  442. 'password' => 'xxxxxxxx',
  443. 'dbname' => 'test',
  444. 'driver_options' => $pdoParams
  445. );
  446. $db = Zend_Db::factory('Pdo_Mysql', $params);
  447. echo $db->getConnection()
  448. ->getAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY);
  449. ]]></programlisting>
  450. </example>
  451. <example id="zend.db.adapter.connecting.parameters.example4">
  452. <title>Passing Serialization Options to the Factory</title>
  453. <programlisting language="php"><![CDATA[
  454. $options = array(
  455. Zend_Db::ALLOW_SERIALIZATION => false
  456. );
  457. $params = array(
  458. 'host' => '127.0.0.1',
  459. 'username' => 'webuser',
  460. 'password' => 'xxxxxxxx',
  461. 'dbname' => 'test',
  462. 'options' => $options
  463. );
  464. $db = Zend_Db::factory('Pdo_Mysql', $params);
  465. ]]></programlisting>
  466. </example>
  467. </sect3>
  468. <sect3 id="zend.db.adapter.connecting.getconnection">
  469. <title>Managing Lazy Connections</title>
  470. <para>
  471. Creating an instance of an Adapter class does not immediately
  472. connect to the <acronym>RDBMS</acronym> server. The Adapter saves the connection
  473. parameters, and makes the actual connection on demand, the
  474. first time you need to execute a query. This ensures that
  475. creating an Adapter object is quick and inexpensive. You can
  476. create an instance of an Adapter even if you are not certain
  477. that you need to run any database queries during the current
  478. request your application is serving.
  479. </para>
  480. <para>
  481. If you need to force the Adapter to connect to the <acronym>RDBMS</acronym>, use
  482. the <methodname>getConnection()</methodname> method. This method returns
  483. an object for the connection as represented by the respective
  484. <acronym>PHP</acronym> database extension. For example, if you use any of the
  485. Adapter classes for <acronym>PDO</acronym> drivers, then
  486. <methodname>getConnection()</methodname> returns the <acronym>PDO</acronym> object,
  487. after initiating it as a live connection to the specific database.
  488. </para>
  489. <para>
  490. It can be useful to force the connection if you want to catch
  491. any exceptions it throws as a result of invalid account
  492. credentials, or other failure to connect to the <acronym>RDBMS</acronym> server.
  493. These exceptions are not thrown until the connection is made,
  494. so it can help simplify your application code if you handle the
  495. exceptions in one place, instead of at the time of
  496. the first query against the database.
  497. </para>
  498. <para>
  499. Additionally, an adapter can get serialized to store it, for example,
  500. in a session variable. This can be very useful not only for the
  501. adapter itself, but for other objects that aggregate it, like a
  502. <classname>Zend_Db_Select</classname> object. By default, adapters are allowed
  503. to be serialized, if you don't want it, you should consider passing the
  504. <constant>Zend_Db::ALLOW_SERIALIZATION</constant> option with
  505. <constant>FALSE</constant>, see the example above. To respect lazy connections
  506. principle, the adapter won't reconnect itself after being unserialized. You must
  507. then call <methodname>getConnection()</methodname> yourself. You can make the
  508. adapter auto-reconnect by passing the
  509. <constant>Zend_Db::AUTO_RECONNECT_ON_UNSERIALIZE</constant> with
  510. <constant>TRUE</constant> as an adapter option.
  511. </para>
  512. <example id="zend.db.adapter.connecting.getconnection.example">
  513. <title>Handling connection exceptions</title>
  514. <programlisting language="php"><![CDATA[
  515. try {
  516. $db = Zend_Db::factory('Pdo_Mysql', $parameters);
  517. $db->getConnection();
  518. } catch (Zend_Db_Adapter_Exception $e) {
  519. // perhaps a failed login credential, or perhaps the RDBMS is not running
  520. } catch (Zend_Exception $e) {
  521. // perhaps factory() failed to load the specified Adapter class
  522. }
  523. ]]></programlisting>
  524. </example>
  525. </sect3>
  526. </sect2>
  527. <sect2 id="zend.db.adapter.example-database">
  528. <title>La base de datos de ejemplo</title>
  529. <para>
  530. En la documentación de las clases <classname>Zend_Db</classname>, usamos un
  531. conjunto sencillo de tablas para ilustrar el uso de las
  532. clases y métodos. Estas tablas de ejemplo permiten almacenar
  533. información para localizar bugs en un proyecto de desarrollo
  534. de software. La base de datos contiene cuatro tablas:
  535. </para>
  536. <itemizedlist>
  537. <listitem>
  538. <para>
  539. <emphasis>accounts</emphasis>
  540. almacena información sobre cada usuario que hace el
  541. seguimiento de bugs.
  542. </para>
  543. </listitem>
  544. <listitem>
  545. <para>
  546. <emphasis>products</emphasis>
  547. almacena información sobre cada producto para el que
  548. pueden registrarse bugs.
  549. </para>
  550. </listitem>
  551. <listitem>
  552. <para>
  553. <emphasis>bugs</emphasis>
  554. almacena información sobre bugs, incluyendo el
  555. estado actual del bug, la persona que informó sobre
  556. el bug, la persona que está asignada para corregir
  557. el bug, y la persona que está asignada para
  558. verificar la corrección.
  559. </para>
  560. </listitem>
  561. <listitem>
  562. <para>
  563. <emphasis>bugs_products</emphasis>
  564. stores a relationship between bugs and products.
  565. This implements a many-to-many relationship, because
  566. a given bug may be relevant to multiple products,
  567. and of course a given product can have multiple
  568. bugs.
  569. </para>
  570. </listitem>
  571. </itemizedlist>
  572. <para>
  573. La siguiente definición de datos <acronym>SQL</acronym>en lenguaje
  574. pseudocódigo describe las tablas de esta base de datos de
  575. ejemplo. Estas tablas de ejemplo son usadas ampliamente por
  576. los tests unitarios automatizados de <classname>Zend_Db</classname>.
  577. </para>
  578. <programlisting language="sql"><![CDATA[
  579. CREATE TABLE accounts (
  580. account_name VARCHAR(100) NOT NULL PRIMARY KEY
  581. );
  582. CREATE TABLE products (
  583. product_id INTEGER NOT NULL PRIMARY KEY,
  584. product_name VARCHAR(100)
  585. );
  586. CREATE TABLE bugs (
  587. bug_id INTEGER NOT NULL PRIMARY KEY,
  588. bug_description VARCHAR(100),
  589. bug_status VARCHAR(20),
  590. reported_by VARCHAR(100) REFERENCES accounts(account_name),
  591. assigned_to VARCHAR(100) REFERENCES accounts(account_name),
  592. verified_by VARCHAR(100) REFERENCES accounts(account_name)
  593. );
  594. CREATE TABLE bugs_products (
  595. bug_id INTEGER NOT NULL REFERENCES bugs,
  596. product_id INTEGER NOT NULL REFERENCES products,
  597. PRIMARY KEY (bug_id, product_id)
  598. );
  599. ]]></programlisting>
  600. <para>
  601. Also notice that the <code>bugs</code> table contains multiple
  602. foreign key references to the <code>accounts</code> table.
  603. Each of these foreign keys may reference a different row in the
  604. <code>accounts</code> table for a given bug.
  605. </para>
  606. <para>
  607. The diagram below illustrates the physical data model of the
  608. example database.
  609. </para>
  610. <para>
  611. <inlinegraphic width="387" scale="100" align="center" valign="middle"
  612. fileref="figures/zend.db.adapter.example-database.png" format="PNG" />
  613. </para>
  614. </sect2>
  615. <sect2 id="zend.db.adapter.select">
  616. <title>Reading Query Results</title>
  617. <para>
  618. This section describes methods of the Adapter class with which you
  619. can run SELECT queries and retrieve the query results.
  620. </para>
  621. <sect3 id="zend.db.adapter.select.fetchall">
  622. <title>Fetching a Complete Result Set</title>
  623. <para>
  624. You can run a <acronym>SQL</acronym> SELECT query and retrieve its results in one
  625. step using the <methodname>fetchAll()</methodname> method.
  626. </para>
  627. <para>
  628. The first argument to this method is a string containing a
  629. SELECT statement. Alternatively, the first argument can be an
  630. object of class <link linkend="zend.db.select">Zend_Db_Select</link>.
  631. The Adapter automatically converts this object to a string
  632. representation of the SELECT statement.
  633. </para>
  634. <para>
  635. The second argument to <methodname>fetchAll()</methodname> is an array of
  636. values to substitute for parameter placeholders in the <acronym>SQL</acronym>
  637. statement.
  638. </para>
  639. <example id="zend.db.adapter.select.fetchall.example">
  640. <title>Using fetchAll()</title>
  641. <programlisting language="php"><![CDATA[
  642. $sql = 'SELECT * FROM bugs WHERE bug_id = ?';
  643. $result = $db->fetchAll($sql, 2);
  644. ]]></programlisting>
  645. </example>
  646. </sect3>
  647. <sect3 id="zend.db.adapter.select.fetch-mode">
  648. <title>Changing the Fetch Mode</title>
  649. <para>
  650. By default, <methodname>fetchAll()</methodname> returns an array of
  651. rows, each of which is an associative array. The keys of the
  652. associative array are the columns or column aliases named in
  653. the select query.
  654. </para>
  655. <para>
  656. You can specify a different style of fetching results using the
  657. <methodname>setFetchMode()</methodname> method. The modes supported are
  658. identified by constants:
  659. </para>
  660. <itemizedlist>
  661. <listitem>
  662. <para>
  663. <emphasis>Zend_Db::FETCH_ASSOC</emphasis>:
  664. return data in an array of associative arrays.
  665. The array keys are column names, as strings. This is the default fetch mode
  666. for <classname>Zend_Db_Adapter</classname> classes.
  667. </para>
  668. <para>
  669. Note that if your select-list contains more than one
  670. column with the same name, for example if they are from
  671. two different tables in a JOIN, there can be only one
  672. entry in the associative array for a given name.
  673. If you use the FETCH_ASSOC mode, you should specify
  674. column aliases in your SELECT query to ensure that the
  675. names result in unique array keys.
  676. </para>
  677. <para>
  678. By default, these strings are returned as they are
  679. returned by the database driver. This is typically the
  680. spelling of the column in the <acronym>RDBMS</acronym> server. You can
  681. specify the case for these strings, using the
  682. <constant>Zend_Db::CASE_FOLDING</constant> option.
  683. Specify this when instantiating the Adapter.
  684. See <xref linkend="zend.db.adapter.connecting.parameters.example1" />.
  685. </para>
  686. </listitem>
  687. <listitem>
  688. <para>
  689. <emphasis>Zend_Db::FETCH_NUM</emphasis>:
  690. return data in an array of arrays. The arrays are
  691. indexed by integers, corresponding to the position of
  692. the respective field in the select-list of the query.
  693. </para>
  694. </listitem>
  695. <listitem>
  696. <para>
  697. <emphasis>Zend_Db::FETCH_BOTH</emphasis>:
  698. return data in an array of arrays. The array keys are
  699. both strings as used in the FETCH_ASSOC mode, and
  700. integers as used in the FETCH_NUM mode. Note that the
  701. number of elements in the array is double that which
  702. would be in the array if you used either FETCH_ASSOC
  703. or FETCH_NUM.
  704. </para>
  705. </listitem>
  706. <listitem>
  707. <para>
  708. <emphasis>Zend_Db::FETCH_COLUMN</emphasis>:
  709. return data in an array of values. The value in each array
  710. is the value returned by one column of the result set.
  711. By default, this is the first column, indexed by 0.
  712. </para>
  713. </listitem>
  714. <listitem>
  715. <para>
  716. <emphasis>Zend_Db::FETCH_OBJ</emphasis>:
  717. return data in an array of objects. The default class
  718. is the <acronym>PHP</acronym> built-in class stdClass. Columns of the
  719. result set are available as public properties of the
  720. object.
  721. </para>
  722. </listitem>
  723. </itemizedlist>
  724. <example id="zend.db.adapter.select.fetch-mode.example">
  725. <title>Using setFetchMode()</title>
  726. <programlisting language="php"><![CDATA[
  727. $db->setFetchMode(Zend_Db::FETCH_OBJ);
  728. $result = $db->fetchAll('SELECT * FROM bugs WHERE bug_id = ?', 2);
  729. // $result is an array of objects
  730. echo $result[0]->bug_description;
  731. ]]></programlisting>
  732. </example>
  733. </sect3>
  734. <sect3 id="zend.db.adapter.select.fetchassoc">
  735. <title>Fetching a Result Set as an Associative Array</title>
  736. <para>
  737. The <methodname>fetchAssoc()</methodname> method returns data in an array
  738. of associative arrays, regardless of what value you have set
  739. for the fetch mode.
  740. </para>
  741. <example id="zend.db.adapter.select.fetchassoc.example">
  742. <title>Using fetchAssoc()</title>
  743. <programlisting language="php"><![CDATA[
  744. $db->setFetchMode(Zend_Db::FETCH_OBJ);
  745. $result = $db->fetchAssoc('SELECT * FROM bugs WHERE bug_id = ?', 2);
  746. // $result is an array of associative arrays, in spite of the fetch mode
  747. echo $result[0]['bug_description'];
  748. ]]></programlisting>
  749. </example>
  750. </sect3>
  751. <sect3 id="zend.db.adapter.select.fetchcol">
  752. <title>Fetching a Single Column from a Result Set</title>
  753. <para>
  754. The <methodname>fetchCol()</methodname> method returns data in an array
  755. of values, regardless of the value you have set for the fetch mode.
  756. This only returns the first column returned by the query.
  757. Any other columns returned by the query are discarded.
  758. If you need to return a column other than the first, see
  759. <xref linkend="zend.db.statement.fetching.fetchcolumn" />.
  760. </para>
  761. <example id="zend.db.adapter.select.fetchcol.example">
  762. <title>Using fetchCol()</title>
  763. <programlisting language="php"><![CDATA[
  764. $db->setFetchMode(Zend_Db::FETCH_OBJ);
  765. $result = $db->fetchCol(
  766. 'SELECT bug_description, bug_id FROM bugs WHERE bug_id = ?', 2);
  767. // contains bug_description; bug_id is not returned
  768. echo $result[0];
  769. ]]></programlisting>
  770. </example>
  771. </sect3>
  772. <sect3 id="zend.db.adapter.select.fetchpairs">
  773. <title>Fetching Key-Value Pairs from a Result Set</title>
  774. <para>
  775. The <methodname>fetchPairs()</methodname> method returns data in an array
  776. of key-value pairs, as an associative array with a single entry
  777. per row. The key of this associative array is taken from the
  778. first column returned by the SELECT query. The value is taken
  779. from the second column returned by the SELECT query. Any other
  780. columns returned by the query are discarded.
  781. </para>
  782. <para>
  783. You should design the SELECT query so that the first column
  784. returned has unique values. If there are duplicates values in
  785. the first column, entries in the associative array will be
  786. overwritten.
  787. </para>
  788. <example id="zend.db.adapter.select.fetchpairs.example">
  789. <title>Using fetchPairs()</title>
  790. <programlisting language="php"><![CDATA[
  791. $db->setFetchMode(Zend_Db::FETCH_OBJ);
  792. $result = $db->fetchPairs('SELECT bug_id, bug_status FROM bugs');
  793. echo $result[2];
  794. ]]></programlisting>
  795. </example>
  796. </sect3>
  797. <sect3 id="zend.db.adapter.select.fetchrow">
  798. <title>Fetching a Single Row from a Result Set</title>
  799. <para>
  800. The <methodname>fetchRow()</methodname> method returns data using the
  801. current fetch mode, but it returns only the first row
  802. fetched from the result set.
  803. </para>
  804. <example id="zend.db.adapter.select.fetchrow.example">
  805. <title>Using fetchRow()</title>
  806. <programlisting language="php"><![CDATA[
  807. $db->setFetchMode(Zend_Db::FETCH_OBJ);
  808. $result = $db->fetchRow('SELECT * FROM bugs WHERE bug_id = 2');
  809. // note that $result is a single object, not an array of objects
  810. echo $result->bug_description;
  811. ]]></programlisting>
  812. </example>
  813. </sect3>
  814. <sect3 id="zend.db.adapter.select.fetchone">
  815. <title>Fetching a Single Scalar from a Result Set</title>
  816. <para>
  817. The <methodname>fetchOne()</methodname> method is like a combination
  818. of <methodname>fetchRow()</methodname> with <methodname>fetchCol()</methodname>,
  819. in that it returns data only for the first row fetched from
  820. the result set, and it returns only the value of the first
  821. column in that row. Therefore it returns only a single
  822. scalar value, not an array or an object.
  823. </para>
  824. <example id="zend.db.adapter.select.fetchone.example">
  825. <title>Using fetchOne()</title>
  826. <programlisting language="php"><![CDATA[
  827. $result = $db->fetchOne('SELECT bug_status FROM bugs WHERE bug_id = 2');
  828. // this is a single string value
  829. echo $result;
  830. ]]></programlisting>
  831. </example>
  832. </sect3>
  833. </sect2>
  834. <sect2 id="zend.db.adapter.write">
  835. <title>Writing Changes to the Database</title>
  836. <para>
  837. You can use the Adapter class to write new data or change existing
  838. data in your database. This section describes methods to do these
  839. operations.
  840. </para>
  841. <sect3 id="zend.db.adapter.write.insert">
  842. <title>Inserting Data</title>
  843. <para>
  844. You can add new rows to a table in your database using the
  845. <methodname>insert()</methodname> method. The first argument is a string
  846. that names the table, and the second argument is an associative
  847. array, mapping column names to data values.
  848. </para>
  849. <example id="zend.db.adapter.write.insert.example">
  850. <title>Inserting in a Table</title>
  851. <programlisting language="php"><![CDATA[
  852. $data = array(
  853. 'created_on' => '2007-03-22',
  854. 'bug_description' => 'Something wrong',
  855. 'bug_status' => 'NEW'
  856. );
  857. $db->insert('bugs', $data);
  858. ]]></programlisting>
  859. </example>
  860. <para>
  861. Columns you exclude from the array of data are not specified to
  862. the database. Therefore, they follow the same rules that an
  863. <acronym>SQL</acronym> INSERT statement follows: if the column has a DEFAULT
  864. clause, the column takes that value in the row created,
  865. otherwise the column is left in a NULL state.
  866. </para>
  867. <para>
  868. By default, the values in your data array are inserted using
  869. parameters. This reduces risk of some types of security
  870. issues. You don't need to apply escaping or quoting to values
  871. in the data array.
  872. </para>
  873. <para>
  874. You might need values in the data array to be treated as <acronym>SQL</acronym>
  875. expressions, in which case they should not be quoted. By
  876. default, all data values passed as strings are treated as
  877. string literals. To specify that the value is an <acronym>SQL</acronym>
  878. expression and therefore should not be quoted, pass the value
  879. in the data array as an object of type <classname>Zend_Db_Expr</classname> instead
  880. of a plain string.
  881. </para>
  882. <example id="zend.db.adapter.write.insert.example2">
  883. <title>Inserting Expressions in a Table</title>
  884. <programlisting language="php"><![CDATA[
  885. $data = array(
  886. 'created_on' => new Zend_Db_Expr('CURDATE()'),
  887. 'bug_description' => 'Something wrong',
  888. 'bug_status' => 'NEW'
  889. );
  890. $db->insert('bugs', $data);
  891. ]]></programlisting>
  892. </example>
  893. </sect3>
  894. <sect3 id="zend.db.adapter.write.lastinsertid">
  895. <title>Retrieving a Generated Value</title>
  896. <para>
  897. Some <acronym>RDBMS</acronym> brands support auto-incrementing primary keys.
  898. A table defined this way generates a primary key value
  899. automatically during an INSERT of a new row. The return value
  900. of the <methodname>insert()</methodname> method is <emphasis>not</emphasis>
  901. the last inserted ID, because the table might not have an
  902. auto-incremented column. Instead, the return value is the
  903. number of rows affected (usually 1).
  904. </para>
  905. <para>
  906. If your table is defined with an auto-incrementing primary key,
  907. you can call the <methodname>lastInsertId()</methodname> method after the
  908. insert. This method returns the last value generated in the
  909. scope of the current database connection.
  910. </para>
  911. <example id="zend.db.adapter.write.lastinsertid.example-1">
  912. <title>Using lastInsertId() for an Auto-Increment Key</title>
  913. <programlisting language="php"><![CDATA[
  914. $db->insert('bugs', $data);
  915. // return the last value generated by an auto-increment column
  916. $id = $db->lastInsertId();
  917. ]]></programlisting>
  918. </example>
  919. <para>
  920. Some <acronym>RDBMS</acronym> brands support a sequence object, which generates
  921. unique values to serve as primary key values. To support
  922. sequences, the <methodname>lastInsertId()</methodname> method accepts two
  923. optional string arguments. These arguments name the table and
  924. the column, assuming you have followed the convention that a
  925. sequence is named using the table and column names for which
  926. the sequence generates values, and a suffix "_seq". This is
  927. based on the convention used by PostgreSQL when naming
  928. sequences for SERIAL columns. For example, a table "bugs" with
  929. primary key column "bug_id" would use a sequence named
  930. "bugs_bug_id_seq".
  931. </para>
  932. <example id="zend.db.adapter.write.lastinsertid.example-2">
  933. <title>Using lastInsertId() for a Sequence</title>
  934. <programlisting language="php"><![CDATA[
  935. $db->insert('bugs', $data);
  936. // return the last value generated by sequence 'bugs_bug_id_seq'.
  937. $id = $db->lastInsertId('bugs', 'bug_id');
  938. // alternatively, return the last value generated by sequence 'bugs_seq'.
  939. $id = $db->lastInsertId('bugs');
  940. ]]></programlisting>
  941. </example>
  942. <para>
  943. If the name of your sequence object does not follow this naming
  944. convention, use the <methodname>lastSequenceId()</methodname> method
  945. instead. This method takes a single string argument, naming
  946. the sequence literally.
  947. </para>
  948. <example id="zend.db.adapter.write.lastinsertid.example-3">
  949. <title>Using lastSequenceId()</title>
  950. <programlisting language="php"><![CDATA[
  951. $db->insert('bugs', $data);
  952. // return the last value generated by sequence 'bugs_id_gen'.
  953. $id = $db->lastSequenceId('bugs_id_gen');
  954. ]]></programlisting>
  955. </example>
  956. <para>
  957. For <acronym>RDBMS</acronym> brands that don't support sequences, including MySQL,
  958. Microsoft <acronym>SQL</acronym> Server, and SQLite, the arguments to the
  959. lastInsertId() method are ignored, and the value returned is the
  960. most recent value generated for any table by INSERT operations
  961. during the current connection. For these <acronym>RDBMS</acronym> brands, the
  962. lastSequenceId() method always returns <constant>NULL</constant>.
  963. </para>
  964. <note>
  965. <title>Why Not Use "SELECT MAX(id) FROM table"?</title>
  966. <para>
  967. Sometimes this query returns the most recent primary key
  968. value inserted into the table. However, this technique
  969. is not safe to use in an environment where multiple clients are
  970. inserting records to the database. It is possible, and
  971. therefore is bound to happen eventually, that another
  972. client inserts another row in the instant between the
  973. insert performed by your client application and your query
  974. for the MAX(id) value. Thus the value returned does not
  975. identify the row you inserted, it identifies the row
  976. inserted by some other client. There is no way to know
  977. when this has happened.
  978. </para>
  979. <para>
  980. Using a strong transaction isolation mode such as
  981. "repeatable read" can mitigate this risk, but some <acronym>RDBMS</acronym>
  982. brands don't support the transaction isolation required for
  983. this, or else your application may use a lower transaction
  984. isolation mode by design.
  985. </para>
  986. <para>
  987. Furthermore, using an expression like "MAX(id)+1" to generate
  988. a new value for a primary key is not safe, because two clients
  989. could do this query simultaneously, and then both use the same
  990. calculated value for their next INSERT operation.
  991. </para>
  992. <para>
  993. All <acronym>RDBMS</acronym> brands provide mechanisms to generate unique
  994. values, and to return the last value generated. These
  995. mechanisms necessarily work outside of the scope of
  996. transaction isolation, so there is no chance of two clients
  997. generating the same value, and there is no chance that the
  998. value generated by another client could be reported to your
  999. client's connection as the last value generated.
  1000. </para>
  1001. </note>
  1002. </sect3>
  1003. <sect3 id="zend.db.adapter.write.update">
  1004. <title>Updating Data</title>
  1005. <para>
  1006. You can update rows in a database table using the
  1007. <methodname>update()</methodname> method of an Adapter. This method takes
  1008. three arguments: the first is the name of the table; the
  1009. second is an associative array mapping columns to change to new
  1010. values to assign to these columns.
  1011. </para>
  1012. <para>
  1013. The values in the data array are treated as string literals.
  1014. See <xref linkend="zend.db.adapter.write.insert" />
  1015. for information on using <acronym>SQL</acronym> expressions in the data array.
  1016. </para>
  1017. <para>
  1018. The third argument is a string containing an <acronym>SQL</acronym> expression
  1019. that is used as criteria for the rows to change. The values
  1020. and identifiers in this argument are not quoted or escaped.
  1021. You are responsible for ensuring that any dynamic content is
  1022. interpolated into this string safely.
  1023. See <xref linkend="zend.db.adapter.quoting" />
  1024. for methods to help you do this.
  1025. </para>
  1026. <para>
  1027. The return value is the number of rows affected by the update
  1028. operation.
  1029. </para>
  1030. <example id="zend.db.adapter.write.update.example">
  1031. <title>Updating Rows</title>
  1032. <programlisting language="php"><![CDATA[
  1033. $data = array(
  1034. 'updated_on' => '2007-03-23',
  1035. 'bug_status' => 'FIXED'
  1036. );
  1037. $n = $db->update('bugs', $data, 'bug_id = 2');
  1038. ]]></programlisting>
  1039. </example>
  1040. <para>
  1041. If you omit the third argument, then all rows in the database
  1042. table are updated with the values specified in the data array.
  1043. </para>
  1044. <para>
  1045. If you provide an array of strings as the third argument, these
  1046. strings are joined together as terms in an expression separated
  1047. by <constant>AND</constant> operators.
  1048. </para>
  1049. <example id="zend.db.adapter.write.update.example-array">
  1050. <title>Updating Rows Using an Array of Expressions</title>
  1051. <programlisting language="php"><![CDATA[
  1052. $data = array(
  1053. 'updated_on' => '2007-03-23',
  1054. 'bug_status' => 'FIXED'
  1055. );
  1056. $where[] = "reported_by = 'goofy'";
  1057. $where[] = "bug_status = 'OPEN'";
  1058. $n = $db->update('bugs', $data, $where);
  1059. // Resulting SQL is:
  1060. // UPDATE "bugs" SET "update_on" = '2007-03-23', "bug_status" = 'FIXED'
  1061. // WHERE ("reported_by" = 'goofy') AND ("bug_status" = 'OPEN')
  1062. ]]></programlisting>
  1063. </example>
  1064. </sect3>
  1065. <sect3 id="zend.db.adapter.write.delete">
  1066. <title>Deleting Data</title>
  1067. <para>
  1068. You can delete rows from a database table using the
  1069. <methodname>delete()</methodname> method. This method takes two arguments:
  1070. the first is a string naming the table.
  1071. </para>
  1072. <para>
  1073. The second argument is a string containing an <acronym>SQL</acronym> expression
  1074. that is used as criteria for the rows to delete. The values
  1075. and identifiers in this argument are not quoted or escaped.
  1076. You are responsible for ensuring that any dynamic content is
  1077. interpolated into this string safely.
  1078. See <xref linkend="zend.db.adapter.quoting" />
  1079. for methods to help you do this.
  1080. </para>
  1081. <para>
  1082. The return value is the number of rows affected by the delete
  1083. operation.
  1084. </para>
  1085. <example id="zend.db.adapter.write.delete.example">
  1086. <title>Deleting Rows</title>
  1087. <programlisting language="php"><![CDATA[
  1088. $n = $db->delete('bugs', 'bug_id = 3');
  1089. ]]></programlisting>
  1090. </example>
  1091. <para>
  1092. If you omit the second argument, the result is that all rows in
  1093. the database table are deleted.
  1094. </para>
  1095. <para>
  1096. If you provide an array of strings as the second argument, these
  1097. strings are joined together as terms in an expression separated
  1098. by <constant>AND</constant> operators.
  1099. </para>
  1100. </sect3>
  1101. </sect2>
  1102. <sect2 id="zend.db.adapter.quoting">
  1103. <title>Quoting Values and Identifiers</title>
  1104. <para>
  1105. When you form SQL queries, often it is the case that you need to
  1106. include the values of PHP variables in SQL expressions. This is
  1107. risky, because if the value in a PHP string contains certain
  1108. symbols, such as the quote symbol, it could result in invalid SQL.
  1109. For example, notice the imbalanced quote characters in the
  1110. following query:
  1111. <programlisting language="php"><![CDATA[
  1112. $name = "O'Reilly";
  1113. $sql = "SELECT * FROM bugs WHERE reported_by = '$name'";
  1114. echo $sql;
  1115. // SELECT * FROM bugs WHERE reported_by = 'O'Reilly'
  1116. ]]></programlisting>
  1117. </para>
  1118. <para>
  1119. Even worse is the risk that such code mistakes might be exploited
  1120. deliberately by a person who is trying to manipulate the function
  1121. of your web application. If they can specify the value of a <acronym>PHP</acronym>
  1122. variable through the use of an <acronym>HTTP</acronym> parameter or other mechanism,
  1123. they might be able to make your <acronym>SQL</acronym> queries do things that you
  1124. didn't intend them to do, such as return data to which the person
  1125. should not have privilege to read. This is a serious and widespread
  1126. technique for violating application security, known as "SQL Injection" (see <ulink
  1127. url="http://en.wikipedia.org/wiki/SQL_Injection">http://en.wikipedia.org/wiki/SQL_Injection</ulink>).
  1128. </para>
  1129. <para>
  1130. The <classname>Zend_Db</classname> Adapter class provides convenient functions to help
  1131. you reduce vulnerabilities to <acronym>SQL</acronym> Injection attacks in your <acronym>PHP</acronym> code.
  1132. The solution is to escape special characters such as quotes in <acronym>PHP</acronym>
  1133. values before they are interpolated into your <acronym>SQL</acronym> strings.
  1134. This protects against both accidental and deliberate manipulation
  1135. of <acronym>SQL</acronym> strings by <acronym>PHP</acronym> variables that contain special characters.
  1136. </para>
  1137. <sect3 id="zend.db.adapter.quoting.quote">
  1138. <title>Using quote()</title>
  1139. <para>
  1140. The <methodname>quote()</methodname> method accepts a single argument, a
  1141. scalar string value. It returns the value with special
  1142. characters escaped in a manner appropriate for the <acronym>RDBMS</acronym> you
  1143. are using, and surrounded by string value delimiters. The
  1144. standard <acronym>SQL</acronym> string value delimiter is the single-quote
  1145. (<code>'</code>).
  1146. </para>
  1147. <example id="zend.db.adapter.quoting.quote.example">
  1148. <title>Using quote()</title>
  1149. <programlisting language="php"><![CDATA[
  1150. $name = $db->quote("O'Reilly");
  1151. echo $name;
  1152. // 'O\'Reilly'
  1153. $sql = "SELECT * FROM bugs WHERE reported_by = $name";
  1154. echo $sql;
  1155. // SELECT * FROM bugs WHERE reported_by = 'O\'Reilly'
  1156. ]]></programlisting>
  1157. </example>
  1158. <para>
  1159. Note that the return value of <methodname>quote()</methodname> includes the
  1160. quote delimiters around the string. This is different from
  1161. some functions that escape special characters but do not add
  1162. the quote delimiters, for example <ulink
  1163. url="http://www.php.net/mysqli_real_escape_string">mysql_real_escape_string()</ulink>.
  1164. </para>
  1165. <para>
  1166. Values may need to be quoted or not quoted according to the SQL
  1167. datatype context in which they are used. For instance, in some
  1168. RDBMS brands, an integer value must not be quoted as a string
  1169. if it is compared to an integer-type column or expression.
  1170. In other words, the following is an error in some SQL
  1171. implementations, assuming <code>intColumn</code> has a SQL
  1172. datatype of <constant>INTEGER</constant>
  1173. <programlisting language="php"><![CDATA[
  1174. SELECT * FROM atable WHERE intColumn = '123'
  1175. ]]></programlisting>
  1176. </para>
  1177. <para>
  1178. You can use the optional second argument to the
  1179. <methodname>quote()</methodname> method to apply quoting selectively for
  1180. the <acronym>SQL</acronym> datatype you specify.
  1181. </para>
  1182. <example id="zend.db.adapter.quoting.quote.example-2">
  1183. <title>Using quote() with a SQL Type</title>
  1184. <programlisting language="php"><![CDATA[
  1185. $value = '1234';
  1186. $sql = 'SELECT * FROM atable WHERE intColumn = '
  1187. . $db->quote($value, 'INTEGER');
  1188. ]]></programlisting>
  1189. </example>
  1190. <para>
  1191. Each <classname>Zend_Db_Adapter</classname> class has encoded the names of numeric
  1192. <acronym>SQL</acronym> datatypes for the respective brand of <acronym>RDBMS</acronym>. You can also
  1193. use the constants <constant>Zend_Db::INT_TYPE</constant>,
  1194. <constant>Zend_Db::BIGINT_TYPE</constant>, and
  1195. <constant>Zend_Db::FLOAT_TYPE</constant> to write code in a more
  1196. <acronym>RDBMS</acronym>-independent way.
  1197. </para>
  1198. <para>
  1199. <classname>Zend_Db_Table</classname> specifies <acronym>SQL</acronym> types to
  1200. <methodname>quote()</methodname> automatically when generating <acronym>SQL</acronym> queries that
  1201. reference a table's key columns.
  1202. </para>
  1203. </sect3>
  1204. <sect3 id="zend.db.adapter.quoting.quote-into">
  1205. <title>Using quoteInto()</title>
  1206. <para>
  1207. The most typical usage of quoting is to interpolate a <acronym>PHP</acronym>
  1208. variable into a <acronym>SQL</acronym> expression or statement. You can use the
  1209. <methodname>quoteInto()</methodname> method to do this in one step. This
  1210. method takes two arguments: the first argument is a string
  1211. containing a placeholder symbol (<code>?</code>), and the
  1212. second argument is a value or <acronym>PHP</acronym> variable that should be
  1213. substituted for that placeholder.
  1214. </para>
  1215. <para>
  1216. The placeholder symbol is the same symbol used by many <acronym>RDBMS</acronym>
  1217. brands for positional parameters, but the
  1218. <methodname>quoteInto()</methodname> method only emulates query parameters.
  1219. The method simply interpolates the value into the string,
  1220. escapes special characters, and applies quotes around it.
  1221. True query parameters maintain the separation between the <acronym>SQL</acronym>
  1222. string and the parameters as the statement is parsed in the
  1223. <acronym>RDBMS</acronym> server.
  1224. </para>
  1225. <example id="zend.db.adapter.quoting.quote-into.example">
  1226. <title>Using quoteInto()</title>
  1227. <programlisting language="php"><![CDATA[
  1228. $sql = $db->quoteInto("SELECT * FROM bugs WHERE reported_by = ?", "O'Reilly");
  1229. echo $sql;
  1230. // SELECT * FROM bugs WHERE reported_by = 'O\'Reilly'
  1231. ]]></programlisting>
  1232. </example>
  1233. <para>
  1234. You can use the optional third parameter of
  1235. <methodname>quoteInto()</methodname> to specify the <acronym>SQL</acronym> datatype. Numeric
  1236. datatypes are not quoted, and other types are quoted.
  1237. </para>
  1238. <example id="zend.db.adapter.quoting.quote-into.example-2">
  1239. <title>Using quoteInto() with a SQL Type</title>
  1240. <programlisting language="php"><![CDATA[
  1241. $sql = $db
  1242. ->quoteInto("SELECT * FROM bugs WHERE bug_id = ?", '1234', 'INTEGER');
  1243. echo $sql;
  1244. // SELECT * FROM bugs WHERE reported_by = 1234
  1245. ]]></programlisting>
  1246. </example>
  1247. </sect3>
  1248. <sect3 id="zend.db.adapter.quoting.quote-identifier">
  1249. <title>Using quoteIdentifier()</title>
  1250. <para>
  1251. Values are not the only part of <acronym>SQL</acronym> syntax that might need to
  1252. be variable. If you use <acronym>PHP</acronym> variables to name tables, columns,
  1253. or other identifiers in your <acronym>SQL</acronym> statements, you might need to
  1254. quote these strings too. By default, <acronym>SQL</acronym> identifiers have
  1255. syntax rules like <acronym>PHP</acronym> and most other programming languages.
  1256. For example, identifiers should not contain spaces, certain
  1257. punctuation or special characters, or international characters.
  1258. Also certain words are reserved for <acronym>SQL</acronym> syntax, and should not
  1259. be used as identifiers.
  1260. </para>
  1261. <para>
  1262. However, <acronym>SQL</acronym> has a feature called <emphasis>delimited identifiers</emphasis>,
  1263. which allows broader choices for the spelling of identifiers.
  1264. If you enclose a <acronym>SQL</acronym> identifier in the proper types of quotes,
  1265. you can use identifiers with spellings that would be invalid
  1266. without the quotes. Delimited identifiers can contain spaces,
  1267. punctuation, or international characters. You can also use <acronym>SQL</acronym>
  1268. reserved words if you enclose them in identifier delimiters.
  1269. </para>
  1270. <para>
  1271. The <methodname>quoteIdentifier()</methodname> method works like
  1272. <methodname>quote()</methodname>, but it applies the identifier delimiter
  1273. characters to the string according to the type of Adapter you
  1274. use. For example, standard <acronym>SQL</acronym> uses double-quotes
  1275. (<code>"</code>) for identifier delimiters, and most <acronym>RDBMS</acronym>
  1276. brands use that symbol. MySQL uses back-quotes
  1277. (<code>`</code>) by default. The
  1278. <methodname>quoteIdentifier()</methodname> method also escapes special
  1279. characters within the string argument.
  1280. </para>
  1281. <example id="zend.db.adapter.quoting.quote-identifier.example">
  1282. <title>Using quoteIdentifier()</title>
  1283. <programlisting language="php"><![CDATA[
  1284. // we might have a table name that is an SQL reserved word
  1285. $tableName = $db->quoteIdentifier("order");
  1286. $sql = "SELECT * FROM $tableName";
  1287. echo $sql
  1288. // SELECT * FROM "order"
  1289. ]]></programlisting>
  1290. </example>
  1291. <para>
  1292. <acronym>SQL</acronym> delimited identifiers are case-sensitive, unlike unquoted
  1293. identifiers. Therefore, if you use delimited identifiers, you
  1294. must use the spelling of the identifier exactly as it is stored
  1295. in your schema, including the case of the letters.
  1296. </para>
  1297. <para>
  1298. In most cases where <acronym>SQL</acronym> is generated within <classname>Zend_Db</classname> classes,
  1299. the default is that all identifiers are delimited
  1300. automatically. You can change this behavior with the option
  1301. <constant>Zend_Db::AUTO_QUOTE_IDENTIFIERS</constant>. Specify this
  1302. when instantiating the Adapter.
  1303. See <xref linkend="zend.db.adapter.connecting.parameters.example2" />.
  1304. </para>
  1305. </sect3>
  1306. </sect2>
  1307. <sect2 id="zend.db.adapter.transactions">
  1308. <title>Controlling Database Transactions</title>
  1309. <para>
  1310. Databases define transactions as logical units of work that can be
  1311. committed or rolled back as a single change, even if they operate
  1312. on multiple tables. All queries to a database are executed within
  1313. the context of a transaction, even if the database driver manages
  1314. them implicitly. This is called <emphasis>auto-commit</emphasis>
  1315. mode, in which the database driver creates a transaction for every
  1316. statement you execute, and commits that transaction after your
  1317. <acronym>SQL</acronym> statement has been executed. By default, all <classname>Zend_Db</classname> Adapter
  1318. classes operate in auto-commit mode.
  1319. </para>
  1320. <para>
  1321. Alternatively, you can specify the beginning and resolution of a
  1322. transaction, and thus control how many <acronym>SQL</acronym> queries are included in
  1323. a single group that is committed (or rolled back) as a single
  1324. operation. Use the <methodname>beginTransaction()</methodname> method to
  1325. initiate a transaction. Subsequent <acronym>SQL</acronym> statements are executed in
  1326. the context of the same transaction until you resolve it
  1327. explicitly.
  1328. </para>
  1329. <para>
  1330. To resolve the transaction, use either the <methodname>commit()</methodname> or
  1331. <methodname>rollBack()</methodname> methods. The <methodname>commit()</methodname>
  1332. method marks changes made during your transaction as committed, which
  1333. means the effects of these changes are shown in queries run in
  1334. other transactions.
  1335. </para>
  1336. <para>
  1337. The <methodname>rollBack()</methodname> method does the opposite: it discards
  1338. the changes made during your transaction. The changes are
  1339. effectively undone, and the state of the data returns to how it was
  1340. before you began your transaction. However, rolling back your
  1341. transaction has no effect on changes made by other transactions
  1342. running concurrently.
  1343. </para>
  1344. <para>
  1345. After you resolve this transaction, <classname>Zend_Db_Adapter</classname>
  1346. returns to auto-commit mode until you call
  1347. <methodname>beginTransaction()</methodname> again.
  1348. </para>
  1349. <example id="zend.db.adapter.transactions.example">
  1350. <title>Managing a Transaction to Ensure Consistency</title>
  1351. <programlisting language="php"><![CDATA[
  1352. // Start a transaction explicitly.
  1353. $db->beginTransaction();
  1354. try {
  1355. // Attempt to execute one or more queries:
  1356. $db->query(...);
  1357. $db->query(...);
  1358. $db->query(...);
  1359. // If all succeed, commit the transaction and all changes
  1360. // are committed at once.
  1361. $db->commit();
  1362. } catch (Exception $e) {
  1363. // If any of the queries failed and threw an exception,
  1364. // we want to roll back the whole transaction, reversing
  1365. // changes made in the transaction, even those that succeeded.
  1366. // Thus all changes are committed together, or none are.
  1367. $db->rollBack();
  1368. echo $e->getMessage();
  1369. }
  1370. ]]></programlisting>
  1371. </example>
  1372. </sect2>
  1373. <sect2 id="zend.db.adapter.list-describe">
  1374. <title>Listing and Describing Tables</title>
  1375. <para>
  1376. The <methodname>listTables()</methodname> method returns an array of strings,
  1377. naming all tables in the current database.
  1378. </para>
  1379. <para>
  1380. The <methodname>describeTable()</methodname> method returns an associative
  1381. array of metadata about a table. Specify the name of the table
  1382. as a string in the first argument to this method. The second
  1383. argument is optional, and names the schema in which the table
  1384. exists.
  1385. </para>
  1386. <para>
  1387. The keys of the associative array returned are the column names of
  1388. the table. The value corresponding to each column is also an
  1389. associative array, with the following keys and values:
  1390. </para>
  1391. <table frame="all" cellpadding="5" id="zend.db.adapter.list-describe.metadata">
  1392. <title>Metadata Fields Returned by describeTable()</title>
  1393. <tgroup cols="3" align="left" colsep="1" rowsep="1">
  1394. <thead>
  1395. <row>
  1396. <entry>Key</entry>
  1397. <entry>Type</entry>
  1398. <entry>Description</entry>
  1399. </row>
  1400. </thead>
  1401. <tbody>
  1402. <row>
  1403. <entry><constant>SCHEMA_NAME</constant></entry>
  1404. <entry>(string)</entry>
  1405. <entry>Name of the database schema in which this table exists.</entry>
  1406. </row>
  1407. <row>
  1408. <entry><constant>TABLE_NAME</constant></entry>
  1409. <entry>(string)</entry>
  1410. <entry>Name of the table to which this column belongs.</entry>
  1411. </row>
  1412. <row>
  1413. <entry><constant>COLUMN_NAME</constant></entry>
  1414. <entry>(string)</entry>
  1415. <entry>Name of the column.</entry>
  1416. </row>
  1417. <row>
  1418. <entry><constant>COLUMN_POSITION</constant></entry>
  1419. <entry>(integer)</entry>
  1420. <entry>Ordinal position of the column in the table.</entry>
  1421. </row>
  1422. <row>
  1423. <entry><constant>DATA_TYPE</constant></entry>
  1424. <entry>(string)</entry>
  1425. <entry>RDBMS name of the datatype of the column.</entry>
  1426. </row>
  1427. <row>
  1428. <entry><constant>DEFAULT</constant></entry>
  1429. <entry>(string)</entry>
  1430. <entry>Default value for the column, if any.</entry>
  1431. </row>
  1432. <row>
  1433. <entry><constant>NULLABLE</constant></entry>
  1434. <entry>(boolean)</entry>
  1435. <entry>
  1436. True if the column accepts <acronym>SQL</acronym> NULLs, false if the column has a NOT NULL
  1437. constraint.
  1438. </entry>
  1439. </row>
  1440. <row>
  1441. <entry><constant>LENGTH</constant></entry>
  1442. <entry>(integer)</entry>
  1443. <entry>Length or size of the column as reported by the <acronym>RDBMS</acronym>.</entry>
  1444. </row>
  1445. <row>
  1446. <entry><constant>SCALE</constant></entry>
  1447. <entry>(integer)</entry>
  1448. <entry>Scale of <acronym>SQL</acronym> NUMERIC or <constant>DECIMAL</constant> type.</entry>
  1449. </row>
  1450. <row>
  1451. <entry><constant>PRECISION</constant></entry>
  1452. <entry>(integer)</entry>
  1453. <entry>Precision of <acronym>SQL</acronym> NUMERIC or <constant>DECIMAL</constant> type.</entry>
  1454. </row>
  1455. <row>
  1456. <entry><constant>UNSIGNED</constant></entry>
  1457. <entry>(boolean)</entry>
  1458. <entry>True if an integer-based type is reported as <constant>UNSIGNED</constant>.</entry>
  1459. </row>
  1460. <row>
  1461. <entry><constant>PRIMARY</constant></entry>
  1462. <entry>(boolean)</entry>
  1463. <entry>True if the column is part of the primary key of this table.</entry>
  1464. </row>
  1465. <row>
  1466. <entry><constant>PRIMARY_POSITION</constant></entry>
  1467. <entry>(integer)</entry>
  1468. <entry>Ordinal position (1-based) of the column in the primary key.</entry>
  1469. </row>
  1470. <row>
  1471. <entry><constant>IDENTITY</constant></entry>
  1472. <entry>(boolean)</entry>
  1473. <entry>True if the column uses an auto-generated value.</entry>
  1474. </row>
  1475. </tbody>
  1476. </tgroup>
  1477. </table>
  1478. <note>
  1479. <title>How the IDENTITY Metadata Field Relates to Specific RDBMSs</title>
  1480. <para>
  1481. The IDENTITY metadata field was chosen as an 'idiomatic' term to
  1482. represent a relation to surrogate keys. This field can be
  1483. commonly known by the following values:-
  1484. </para>
  1485. <itemizedlist>
  1486. <listitem>
  1487. <para>
  1488. <constant>IDENTITY</constant> - DB2, MSSQL
  1489. </para>
  1490. </listitem>
  1491. <listitem>
  1492. <para>
  1493. <constant>AUTO_INCREMENT</constant> - MySQL
  1494. </para>
  1495. </listitem>
  1496. <listitem>
  1497. <para>
  1498. <constant>SERIAL</constant> - PostgreSQL
  1499. </para>
  1500. </listitem>
  1501. <listitem>
  1502. <para>
  1503. <constant>SEQUENCE</constant> - Oracle
  1504. </para>
  1505. </listitem>
  1506. </itemizedlist>
  1507. </note>
  1508. <para>
  1509. If no table exists matching the table name and optional schema name
  1510. specified, then <methodname>describeTable()</methodname> returns an empty array.
  1511. </para>
  1512. </sect2>
  1513. <sect2 id="zend.db.adapter.closing">
  1514. <title>Closing a Connection</title>
  1515. <para>
  1516. Normally it is not necessary to close a database connection. <acronym>PHP</acronym>
  1517. automatically cleans up all resources and the end of a request.
  1518. Database extensions are designed to close the connection as the
  1519. reference to the resource object is cleaned up.
  1520. </para>
  1521. <para>
  1522. However, if you have a long-duration <acronym>PHP</acronym> script that initiates many
  1523. database connections, you might need to close the connection, to avoid
  1524. exhausting the capacity of your <acronym>RDBMS</acronym> server. You can use the
  1525. Adapter's <methodname>closeConnection()</methodname> method to explicitly close
  1526. the underlying database connection.
  1527. </para>
  1528. <para>
  1529. Since release 1.7.2, you could check you are currently connected to the <acronym>RDBMS</acronym>
  1530. server with the method <methodname>isConnected()</methodname>. This means that a
  1531. connection resource has been initiated and wasn't closed. This function is not
  1532. currently able to test for example a server side closing of the connection. This is
  1533. internally use to close the connection. It allow you to close the connection
  1534. multiple times without errors. It was already the case before 1.7.2 for <acronym>PDO</acronym>
  1535. adapters but not for the others.
  1536. </para>
  1537. <example id="zend.db.adapter.closing.example">
  1538. <title>Closing a Database Connection</title>
  1539. <programlisting language="php"><![CDATA[
  1540. $db->closeConnection();
  1541. ]]></programlisting>
  1542. </example>
  1543. <note>
  1544. <title>Does Zend_Db Support Persistent Connections?</title>
  1545. <para>
  1546. Yes, persistence is supported through the addition of
  1547. the <code>persistent</code> flag set to true in the
  1548. configuration (not driver_configuration) of an adapter
  1549. in <classname>Zend_Db</classname>.
  1550. </para>
  1551. <example id="zend.db.adapter.connecting.persistence.example">
  1552. <title>Using the Persitence Flag with the Oracle Adapter</title>
  1553. <programlisting language="php"><![CDATA[
  1554. $db = Zend_Db::factory('Oracle', array(
  1555. 'host' => '127.0.0.1',
  1556. 'username' => 'webuser',
  1557. 'password' => 'xxxxxxxx',
  1558. 'dbname' => 'test',
  1559. 'persistent' => true
  1560. ));
  1561. ]]></programlisting>
  1562. </example>
  1563. <para>
  1564. Please note that using persistent connections can cause an
  1565. excess of idle connections on the <acronym>RDBMS</acronym> server, which causes
  1566. more problems than any performance gain you might achieve by
  1567. reducing the overhead of making connections.
  1568. </para>
  1569. <para>
  1570. Database connections have state. That is, some objects in the
  1571. <acronym>RDBMS</acronym> server exist in session scope. Examples are locks, user
  1572. variables, temporary tables, and information about the most
  1573. recently executed query, such as rows affected, and last
  1574. generated id value. If you use persistent connections, your
  1575. application could access invalid or privileged data that were
  1576. created in a previous <acronym>PHP</acronym> request.
  1577. </para>
  1578. <para>
  1579. Currently, only Oracle, DB2, and the <acronym>PDO</acronym> adapters (where
  1580. specified by <acronym>PHP</acronym>) support persistence in <classname>Zend_Db</classname>.
  1581. </para>
  1582. </note>
  1583. </sect2>
  1584. <sect2 id="zend.db.adapter.other-statements">
  1585. <title>Running Other Database Statements</title>
  1586. <para>
  1587. There might be cases in which you need to access the connection
  1588. object directly, as provided by the <acronym>PHP</acronym> database extension. Some
  1589. of these extensions may offer features that are not surfaced by
  1590. methods of <classname>Zend_Db_Adapter_Abstract</classname>.
  1591. </para>
  1592. <para>
  1593. For example, all <acronym>SQL</acronym> statements run by <classname>Zend_Db</classname> are prepared, then
  1594. executed. However, some database features are incompatible with
  1595. prepared statements. DDL statements like CREATE and ALTER cannot
  1596. be prepared in MySQL. Also, <acronym>SQL</acronym> statements don't benefit from the <ulink
  1597. url="http://dev.mysql.com/doc/refman/5.1/en/query-cache-how.html">MySQL Query
  1598. Cache</ulink>, prior to MySQL 5.1.17.
  1599. </para>
  1600. <para>
  1601. Most <acronym>PHP</acronym> database extensions provide a method to execute <acronym>SQL</acronym>
  1602. statements without preparing them. For example, in <acronym>PDO</acronym>, this
  1603. method is <methodname>exec()</methodname>. You can access the connection
  1604. object in the <acronym>PHP</acronym> extension directly using getConnection().
  1605. </para>
  1606. <example id="zend.db.adapter.other-statements.example">
  1607. <title>Running a Non-Prepared Statement in a PDO Adapter</title>
  1608. <programlisting language="php"><![CDATA[
  1609. $result = $db->getConnection()->exec('DROP TABLE bugs');
  1610. ]]></programlisting>
  1611. </example>
  1612. <para>
  1613. Similarly, you can access other methods or properties that are
  1614. specific to <acronym>PHP</acronym> database extensions. Be aware, though, that by
  1615. doing this you might constrain your application to the interface
  1616. provided by the extension for a specific brand of <acronym>RDBMS</acronym>.
  1617. </para>
  1618. <para>
  1619. In future versions of <classname>Zend_Db</classname>, there will be opportunities to
  1620. add method entry points for functionality that is common to
  1621. the supported <acronym>PHP</acronym> database extensions. This will not affect
  1622. backward compatibility.
  1623. </para>
  1624. </sect2>
  1625. <sect2 id="zend.db.adapter.server-version">
  1626. <title>Retrieving Server Version</title>
  1627. <para>
  1628. Since release 1.7.2, you could retrieve the server version in <acronym>PHP</acronym> syntax
  1629. style to be able to use <methodname>version_compare()</methodname>. If the information
  1630. isn't available, you will receive <constant>NULL</constant>.
  1631. </para>
  1632. <example id="zend.db.adapter.server-version.example">
  1633. <title>Verifying server version before running a query</title>
  1634. <programlisting language="php"><![CDATA[
  1635. $version = $db->getServerVersion();
  1636. if (!is_null($version)) {
  1637. if (version_compare($version, '5.0.0', '>=')) {
  1638. // do something
  1639. } else {
  1640. // do something else
  1641. }
  1642. } else {
  1643. // impossible to read server version
  1644. }
  1645. ]]></programlisting>
  1646. </example>
  1647. </sect2>
  1648. <sect2 id="zend.db.adapter.adapter-notes">
  1649. <title>Notes on Specific Adapters</title>
  1650. <para>
  1651. This section lists differences between the Adapter classes of which
  1652. you should be aware.
  1653. </para>
  1654. <sect3 id="zend.db.adapter.adapter-notes.ibm-db2">
  1655. <title>IBM DB2</title>
  1656. <itemizedlist>
  1657. <listitem>
  1658. <para>
  1659. Specify this Adapter to the factory() method with the
  1660. name 'Db2'.
  1661. </para>
  1662. </listitem>
  1663. <listitem>
  1664. <para>
  1665. This Adapter uses the <acronym>PHP</acronym> extension ibm_db2.
  1666. </para>
  1667. </listitem>
  1668. <listitem>
  1669. <para>
  1670. IBM DB2 supports both sequences and auto-incrementing
  1671. keys. Therefore the arguments to
  1672. <methodname>lastInsertId()</methodname> are optional. If you give
  1673. no arguments, the Adapter returns the last value
  1674. generated for an auto-increment key. If you give
  1675. arguments, the Adapter returns the last value generated
  1676. by the sequence named according to the convention
  1677. '<emphasis>table</emphasis>_<emphasis>column</emphasis>_seq'.
  1678. </para>
  1679. </listitem>
  1680. </itemizedlist>
  1681. </sect3>
  1682. <sect3 id="zend.db.adapter.adapter-notes.mysqli">
  1683. <title>MySQLi</title>
  1684. <itemizedlist>
  1685. <listitem>
  1686. <para>
  1687. Specify this Adapter to the <methodname>factory()</methodname>
  1688. method with the name 'Mysqli'.
  1689. </para>
  1690. </listitem>
  1691. <listitem>
  1692. <para>
  1693. This Adapter utilizes the <acronym>PHP</acronym> extension mysqli.
  1694. </para>
  1695. </listitem>
  1696. <listitem>
  1697. <para>
  1698. MySQL does not support sequences, so
  1699. <methodname>lastInsertId()</methodname> ignores its arguments and
  1700. always returns the last value generated for an
  1701. auto-increment key. The <methodname>lastSequenceId()</methodname>
  1702. method returns <constant>NULL</constant>.
  1703. </para>
  1704. </listitem>
  1705. </itemizedlist>
  1706. </sect3>
  1707. <sect3 id="zend.db.adapter.adapter-notes.oracle">
  1708. <title>Oracle</title>
  1709. <itemizedlist>
  1710. <listitem>
  1711. <para>
  1712. Specify this Adapter to the <methodname>factory()</methodname>
  1713. method with the name 'Oracle'.
  1714. </para>
  1715. </listitem>
  1716. <listitem>
  1717. <para>
  1718. This Adapter uses the <acronym>PHP</acronym> extension oci8.
  1719. </para>
  1720. </listitem>
  1721. <listitem>
  1722. <para>
  1723. Oracle does not support auto-incrementing keys, so you
  1724. should specify the name of a sequence to
  1725. <methodname>lastInsertId()</methodname> or
  1726. <methodname>lastSequenceId()</methodname>.
  1727. </para>
  1728. </listitem>
  1729. <listitem>
  1730. <para>
  1731. The Oracle extension does not support positional
  1732. parameters. You must use named parameters.
  1733. </para>
  1734. </listitem>
  1735. <listitem>
  1736. <para>
  1737. Currently the <constant>Zend_Db::CASE_FOLDING</constant> option
  1738. is not supported by the Oracle adapter. To use this
  1739. option with Oracle, you must use the <acronym>PDO</acronym> OCI adapter.
  1740. </para>
  1741. </listitem>
  1742. <listitem>
  1743. <para>
  1744. By default, LOB fields are returned as OCI-Lob objects. You could
  1745. retrieve them as string for all requests by using driver options
  1746. <code>'lob_as_string'</code> or for particular request by using
  1747. <methodname>setLobAsString(boolean)</methodname> on adapter or on
  1748. statement.
  1749. </para>
  1750. </listitem>
  1751. </itemizedlist>
  1752. </sect3>
  1753. <sect3 id="zend.db.adapter.adapter-notes.sqlsrv">
  1754. <title>Microsoft SQL Server</title>
  1755. <itemizedlist>
  1756. <listitem>
  1757. <para>
  1758. Specify this Adapter to the <methodname>factory()</methodname> method with
  1759. the name 'Sqlsrv'.
  1760. </para>
  1761. </listitem>
  1762. <listitem>
  1763. <para>
  1764. This Adapter uses the <acronym>PHP</acronym> extension sqlsrv
  1765. </para>
  1766. </listitem>
  1767. <listitem>
  1768. <para>
  1769. Microsoft <acronym>SQL</acronym> Server does not support sequences, so
  1770. <methodname>lastInsertId()</methodname> ignores primary key argument and
  1771. returns the last value generated for an auto-increment key if a table name
  1772. is specified or a last insert query returned id. The
  1773. <methodname>lastSequenceId()</methodname> method returns
  1774. <constant>NULL</constant>.
  1775. </para>
  1776. </listitem>
  1777. <listitem>
  1778. <para>
  1779. <classname>Zend_Db_Adapter_Sqlsrv</classname> sets
  1780. <constant>QUOTED_IDENTIFIER ON</constant> immediately after connecting to
  1781. a <acronym>SQL</acronym> Server database. This makes the driver use the
  1782. standard <acronym>SQL</acronym> identifier delimiter symbol
  1783. (<emphasis>"</emphasis>) instead of the proprietary square-brackets
  1784. syntax <acronym>SQL</acronym> Server uses for delimiting identifiers.
  1785. </para>
  1786. </listitem>
  1787. <listitem>
  1788. <para>
  1789. You can specify <property>driver_options</property> as a key in the options
  1790. array. The value can be a anything from here <ulink
  1791. url="http://msdn.microsoft.com/en-us/library/cc296161(SQL.90).aspx">http://msdn.microsoft.com/en-us/library/cc296161(SQL.90).aspx</ulink>.
  1792. </para>
  1793. </listitem>
  1794. <listitem>
  1795. <para>
  1796. You can use <methodname>setTransactionIsolationLevel()</methodname> to set
  1797. isolation level for current connection. The value can be
  1798. <constant>SQLSRV_TXN_READ_UNCOMMITTED</constant>,
  1799. <constant>SQLSRV_TXN_READ_COMMITTED</constant>,
  1800. <constant>SQLSRV_TXN_REPEATABLE_READ</constant>,
  1801. <constant>SQLSRV_TXN_SNAPSHOT</constant> or
  1802. <constant>SQLSRV_TXN_SERIALIZABLE</constant>.
  1803. </para>
  1804. </listitem>
  1805. <listitem>
  1806. <para>
  1807. As of Zend Framework 1.9, the minimal supported build of the
  1808. <acronym>PHP</acronym> <acronym>SQL</acronym> Server extension from
  1809. Microsoft is 1.0.1924.0. and the <acronym>MSSQL</acronym> Server Native
  1810. Client version 9.00.3042.00.
  1811. </para>
  1812. </listitem>
  1813. </itemizedlist>
  1814. </sect3>
  1815. <sect3 id="zend.db.adapter.adapter-notes.pdo-ibm">
  1816. <title>PDO for IBM DB2 and Informix Dynamic Server (IDS)</title>
  1817. <itemizedlist>
  1818. <listitem>
  1819. <para>
  1820. Specify this Adapter to the <methodname>factory()</methodname>
  1821. method with the name 'Pdo_Ibm'.
  1822. </para>
  1823. </listitem>
  1824. <listitem>
  1825. <para>
  1826. This Adapter uses the <acronym>PHP</acronym> extensions pdo and pdo_ibm.
  1827. </para>
  1828. </listitem>
  1829. <listitem>
  1830. <para>
  1831. You must use at least <acronym>PDO</acronym>_IBM extension version 1.2.2.
  1832. If you have an earlier version of this extension, you
  1833. must upgrade the <acronym>PDO</acronym>_IBM extension from <acronym>PECL</acronym>.
  1834. </para>
  1835. </listitem>
  1836. </itemizedlist>
  1837. </sect3>
  1838. <sect3 id="zend.db.adapter.adapter-notes.pdo-mssql">
  1839. <title>PDO Microsoft SQL Server</title>
  1840. <itemizedlist>
  1841. <listitem>
  1842. <para>
  1843. Specify this Adapter to the <methodname>factory()</methodname>
  1844. method with the name 'Pdo_Mssql'.
  1845. </para>
  1846. </listitem>
  1847. <listitem>
  1848. <para>
  1849. This Adapter uses the <acronym>PHP</acronym> extensions pdo and pdo_mssql.
  1850. </para>
  1851. </listitem>
  1852. <listitem>
  1853. <para>
  1854. Microsoft <acronym>SQL</acronym> Server does not support sequences, so
  1855. <methodname>lastInsertId()</methodname> ignores its arguments and
  1856. always returns the last value generated for an
  1857. auto-increment key. The <methodname>lastSequenceId()</methodname>
  1858. method returns <constant>NULL</constant>.
  1859. </para>
  1860. </listitem>
  1861. <listitem>
  1862. <para>
  1863. If you are working with unicode strings in an encoding other than UCS-2
  1864. (such as UTF-8), you may have to perform a conversion in your application
  1865. code or store the data in a binary column. Please refer to <ulink
  1866. url="http://support.microsoft.com/kb/232580">Microsoft's Knowledge
  1867. Base</ulink> for more information.
  1868. </para>
  1869. </listitem>
  1870. <listitem>
  1871. <para>
  1872. <classname>Zend_Db_Adapter_Pdo_Mssql</classname> sets
  1873. <constant>QUOTED_IDENTIFIER ON</constant> immediately after connecting to a
  1874. <acronym>SQL</acronym> Server database. This makes the driver use the standard <acronym>SQL</acronym> identifier
  1875. delimiter symbol (<code>"</code>) instead of the
  1876. proprietary square-brackets syntax <acronym>SQL</acronym> Server uses for
  1877. delimiting identifiers.
  1878. </para>
  1879. </listitem>
  1880. <listitem>
  1881. <para>
  1882. You can specify <code>pdoType</code> as a key in the
  1883. options array. The value can be "mssql" (the default),
  1884. "dblib", "freetds", or "sybase". This option affects
  1885. the DSN prefix the adapter uses when constructing the
  1886. DSN string. Both "freetds" and "sybase" imply a prefix
  1887. of "sybase:", which is used for the
  1888. <ulink url="http://www.freetds.org/">FreeTDS</ulink> set
  1889. of libraries.
  1890. See also
  1891. <ulink url="http://www.php.net/manual/en/ref.pdo-dblib.connection.php">
  1892. http://www.php.net/manual/en/ref.pdo-dblib.connection.php</ulink>
  1893. for more information on the DSN prefixes used in this driver.
  1894. </para>
  1895. </listitem>
  1896. </itemizedlist>
  1897. </sect3>
  1898. <sect3 id="zend.db.adapter.adapter-notes.pdo-mysql">
  1899. <title>PDO MySQL</title>
  1900. <itemizedlist>
  1901. <listitem>
  1902. <para>
  1903. Specify this Adapter to the <methodname>factory()</methodname>
  1904. method with the name 'Pdo_Mysql'.
  1905. </para>
  1906. </listitem>
  1907. <listitem>
  1908. <para>
  1909. This Adapter uses the <acronym>PHP</acronym> extensions pdo and pdo_mysql.
  1910. </para>
  1911. </listitem>
  1912. <listitem>
  1913. <para>
  1914. MySQL does not support sequences, so
  1915. <methodname>lastInsertId()</methodname> ignores its arguments and
  1916. always returns the last value generated for an
  1917. auto-increment key. The <methodname>lastSequenceId()</methodname>
  1918. method returns <constant>NULL</constant>.
  1919. </para>
  1920. </listitem>
  1921. </itemizedlist>
  1922. </sect3>
  1923. <sect3 id="zend.db.adapter.adapter-notes.pdo-oci">
  1924. <title>PDO Oracle</title>
  1925. <itemizedlist>
  1926. <listitem>
  1927. <para>
  1928. Specify this Adapter to the <methodname>factory()</methodname>
  1929. method with the name 'Pdo_Oci'.
  1930. </para>
  1931. </listitem>
  1932. <listitem>
  1933. <para>
  1934. This Adapter uses the <acronym>PHP</acronym> extensions pdo and pdo_oci.
  1935. </para>
  1936. </listitem>
  1937. <listitem>
  1938. <para>
  1939. Oracle does not support auto-incrementing keys, so you
  1940. should specify the name of a sequence to
  1941. <methodname>lastInsertId()</methodname> or
  1942. <methodname>lastSequenceId()</methodname>.
  1943. </para>
  1944. </listitem>
  1945. </itemizedlist>
  1946. </sect3>
  1947. <sect3 id="zend.db.adapter.adapter-notes.pdo-pgsql">
  1948. <title>PDO PostgreSQL</title>
  1949. <itemizedlist>
  1950. <listitem>
  1951. <para>
  1952. Specify this Adapter to the <methodname>factory()</methodname>
  1953. method with the name 'Pdo_Pgsql'.
  1954. </para>
  1955. </listitem>
  1956. <listitem>
  1957. <para>
  1958. This Adapter uses the <acronym>PHP</acronym> extensions pdo and pdo_pgsql.
  1959. </para>
  1960. </listitem>
  1961. <listitem>
  1962. <para>
  1963. PostgreSQL supports both sequences and auto-incrementing
  1964. keys. Therefore the arguments to
  1965. <methodname>lastInsertId()</methodname> are optional. If you give
  1966. no arguments, the Adapter returns the last value
  1967. generated for an auto-increment key. If you give
  1968. arguments, the Adapter returns the last value generated
  1969. by the sequence named according to the convention
  1970. '<emphasis>table</emphasis>_<emphasis>column</emphasis>_seq'.
  1971. </para>
  1972. </listitem>
  1973. </itemizedlist>
  1974. </sect3>
  1975. <sect3 id="zend.db.adapter.adapter-notes.pdo-sqlite">
  1976. <title>PDO SQLite</title>
  1977. <itemizedlist>
  1978. <listitem>
  1979. <para>
  1980. Specify this Adapter to the <methodname>factory()</methodname>
  1981. method with the name 'Pdo_Sqlite'.
  1982. </para>
  1983. </listitem>
  1984. <listitem>
  1985. <para>
  1986. This Adapter uses the <acronym>PHP</acronym> extensions pdo and pdo_sqlite.
  1987. </para>
  1988. </listitem>
  1989. <listitem>
  1990. <para>
  1991. SQLite does not support sequences, so
  1992. <methodname>lastInsertId()</methodname> ignores its arguments and
  1993. always returns the last value generated for an
  1994. auto-increment key. The <methodname>lastSequenceId()</methodname>
  1995. method returns <constant>NULL</constant>.
  1996. </para>
  1997. </listitem>
  1998. <listitem>
  1999. <para>
  2000. To connect to an SQLite2 database, specify
  2001. <code>'sqlite2'=>true</code> in the array of
  2002. parameters when creating an instance of the
  2003. <classname>Pdo_Sqlite</classname> Adapter.
  2004. </para>
  2005. </listitem>
  2006. <listitem>
  2007. <para>
  2008. To connect to an in-memory SQLite database,
  2009. specify <code>'dbname'=>':memory:'</code> in the
  2010. array of parameters when creating an instance of
  2011. the <classname>Pdo_Sqlite</classname> Adapter.
  2012. </para>
  2013. </listitem>
  2014. <listitem>
  2015. <para>
  2016. Older versions of the SQLite driver for <acronym>PHP</acronym> do not seem
  2017. to support the PRAGMA commands necessary to ensure that
  2018. short column names are used in result sets. If you
  2019. have problems that your result sets are returned with
  2020. keys of the form "tablename.columnname" when you do a
  2021. join query, then you should upgrade to the current
  2022. version of <acronym>PHP</acronym>.
  2023. </para>
  2024. </listitem>
  2025. </itemizedlist>
  2026. </sect3>
  2027. <sect3 id="zend.db.adapter.adapter-notes.firebird">
  2028. <title>Firebird/Interbase</title>
  2029. <itemizedlist>
  2030. <listitem>
  2031. <para>
  2032. This Adapter uses the <acronym>PHP</acronym> extension php_interbase.
  2033. </para>
  2034. </listitem>
  2035. <listitem>
  2036. <para>
  2037. Firebird/interbase does not support auto-incrementing keys,
  2038. so you should specify the name of a sequence to
  2039. <methodname>lastInsertId()</methodname> or
  2040. <methodname>lastSequenceId()</methodname>.
  2041. </para>
  2042. </listitem>
  2043. <listitem>
  2044. <para>
  2045. Currently the <constant>Zend_Db::CASE_FOLDING</constant> option
  2046. is not supported by the Firebird/interbase adapter.
  2047. Unquoted identifiers are automatically returned in
  2048. upper case.
  2049. </para>
  2050. </listitem>
  2051. <listitem>
  2052. <para>Adapter name is <classname>ZendX_Db_Adapter_Firebird</classname>.</para>
  2053. <para>
  2054. Remember to use the param adapterNamespace with value <classname>ZendX_Db_Adapter</classname>.
  2055. </para>
  2056. <para>
  2057. We recommend to update the gds32.dll (or linux equivalent) bundled with php,
  2058. to the same version of the server. For Firebird the equivalent gds32.dll is
  2059. fbclient.dll.
  2060. </para>
  2061. <para>
  2062. By default all identifiers (tables names, fields) are returned in upper
  2063. case.
  2064. </para>
  2065. </listitem>
  2066. </itemizedlist>
  2067. </sect3>
  2068. </sect2>
  2069. </sect1>
  2070. <!--
  2071. vim:se ts=4 sw=4 et:
  2072. -->