Zend_Db_Adapter.xml 92 KB

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