Zend_Db_Adapter.xml 92 KB

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