1 <sect1 id="zend.db.adapter">
3 <title>Zend_Db_Adapter</title>
6 Zend_Db와 관련 클래스들은 Zend Frmework에 기본 데이터 베이스 인터페이스를 제공합니다.
7 Zend_DB_Adapter는 Zend Framework로 만들어진 PHP 어플리케이션이 관계형 데이터베이스에 접속하기 위한 기본 클라스들을 제공합니다. 각 RDBMS의 종류에 따라 각기 다른 아답터가 제공됩니다.
11 Zend_Db의 어댑터는 벤더별 PHP 모듈과 범용 모듈사이에 다리역활을 수행하여,
12 하나의 완성된 PHP 어플리케이션이 최소한의 절차를 거쳐 다른 여러 RDBMS에 적용될수 있게 해줍니다 .
16 어댑터 클래스의 인터페이스는 <ulink url="http://www.php.net/pdo">PHP Data Objects</ulink> 확장 모듈과 매우 유사합니다.
17 Zend_Db는 다음의 RDBMS의 PDO 드라이버를에 대해서 아댑테 클라스를 제공합니다:
49 또한 Zend_DB는 다음 RDBMS에 대하여 사용이 용이한 PHP database의 확장 모듈도 제공하고 있습니다:
55 MySQL, using the <ulink url="http://www.php.net/mysqli">mysqli</ulink> PHP extension
60 Oracle, using the <ulink url="http://www.php.net/oci8">oci8</ulink> PHP extension
65 IBM DB2, using the <ulink url="http://www.php.net/ibm_db2">ibm_db2</ulink> PHP extension
72 각각의 Zend_Db 아댑터들은 PHP extension을 이용하고 있습니다. Zend_DB Adapter를 이용하기 위해서는 PHP 환경 설정을 해당 extension에 맞게 설정해주셔야 합니다.
73 예를 들어, PDO Zend_DB 아댑터를 이용하시려면, PDE extension과 PDO 드라이버를 해당 RDBMS에 맞게 enable 해주셔야 합니다.
77 <sect2 id="zend.db.adapter.connecting">
79 <title>어댑터를 사용한 데이타베이스 접속</title>
82 본 단락에서는 데이타베이스 어댑터의 인스턴스를 생성에대해 다룹니다.
83 이는 PHP 어플리케이션으로 부터 해당 RDBMS서버로의 연결을 생성하는 것을 의미합니다.
87 <sect3 id="zend.db.adapter.connecting.constructor">
89 <title>어댑터 constructor 이용</title>
92 Constructor를 이용하여 아답터의 인스탄트를 생성할수 있습니다.
93 아답터의 Constructor는 인수 하나를 요구하며 그 인수는 커넥션을 생성하기 위한 파라메터의 배열형식입니다.
96 <example id="zend.db.adapter.connecting.constructor.example">
97 <title>아답터의 constructor 사용</title>
98 <programlisting role="php"><![CDATA[<?php
99 require_once 'Zend/Db/Adapter/Pdo/Mysql.php';
101 $db = new Zend_Db_Adapter_Pdo_Mysql(array(
102 'host' => '127.0.0.1',
103 'username' => 'webuser',
104 'password' => 'xxxxxxxx',
112 <sect3 id="zend.db.adapter.connecting.factory">
114 <title>Zend_Db Factory의 사용</title>
117 직접적인 아답터의 Constructor를 이용하는 방법으로, 정적 메소드 <code>Zend_Db::factory()</code>를
118 이용한 아답터의 인스턴스 생성이 있습니다. 이 메소드는 <link linkend="zend.loader.load.class">Zend_Loader::loadClass()</link>를 이용하여 요청에 따라 동적으로 아답터 클라스를 로드 합니다.
122 첫번째 인수는 아답터 클라스의 베이스명을 문자열로 지정합니다. 예를 들어 문자열 'Pdo_Mysql'은 Zend_DB_Adapter_Pdo_Mysql 클라스에 상응하게 됩니다. 두번째 인수는 아답터의 constructor에 넘겨주는 인수의 배열과 같은 형식의 배열이 됩니다.
125 <example id="zend.db.adapter.connecting.factory.example">
126 <title>Adapter factory 메소드의 사용</title>
127 <programlisting role="php"><![CDATA[<?php
128 require_once 'Zend/Db.php';
130 // 자동으로 Zend_Db_Adapter_Pdo_Mysql 클래스를 읽어, 그 인스턴스를 작성합니다.
131 $db = Zend_Db::factory('Pdo_Mysql', array(
132 'host' => '127.0.0.1',
133 'username' => 'webuser',
134 'password' => 'xxxxxxxx',
141 Zend_Db_Adapter_Abstract 클라스를 상속한 독자적인 클라스를 구성하면서, 그 이름에
142 "Zend_Db_Adapter"라는 접두어를 붙이지 않으실경우, 파라메터 배열을 "adapternamespace" 키값으로 시작하셨다면 <code>factory()</code> 메소드를 이용하신 만드신 아답터를 로드하실수 있습니다.
145 <example id="zend.db.adapter.connecting.factory.example2">
146 <title> 커스텀 아답터 클래스를 위한 Adapter factory 메소드 이용하기</title>
147 <programlisting role="php"><![CDATA[<?php
148 require_once 'Zend/Db.php';
150 // Automatically load class MyProject_Db_Adapter_Pdo_Mysql and create an instance of it.
151 $db = Zend_Db::factory('Pdo_Mysql', array(
152 'host' => '127.0.0.1',
153 'username' => 'webuser',
154 'password' => 'xxxxxxxx',
156 'adapterNamespace' => 'MyProject_Db_Adapter'
163 <sect3 id="zend.db.adapter.connecting.factory-config">
165 <title>Zend_Db_Factory와 Zend_Config 이용하기</title>
168 <code>factory()</code> 메소드의 인수로 <link linkend="zend.config">Zend_Config</link>의 오브젝트를 건내줄수도 있습니다.
172 If the first argument is a config object, it is expected to
173 contain a property named <code>adapter</code>, containing the
174 string naming the adapter class name base. Optionally, the object
175 may contain a property named <code>params</code>, with
176 subproperties corresponding to adapter parameter names.
177 This is used only if the second argument of the
178 <code>factory()</code> method is absent.
181 <example id="zend.db.adapter.connecting.factory.example1">
182 <title>Zend_Config 오브젝트와 함께 아댑터 factory 메소드 이용하기</title>
184 아래의 예는, 배열로 부터 생성된 Zend_Config 오브젝트입니다.
185 <link linkend="zend.config.adapters.ini">Zend_Config_Ini</link>
186 또는 <link linkend="zend.config.adapters.xml">Zend_Config_Xml</link>을 이용하여
187 외부 파일로부터도 데이터를 로드 할수 있습니다.
189 <programlisting role="php"><![CDATA[<?php
190 require_once 'Zend/Config.php';
191 require_once 'Zend/Db.php';
193 $config = new Zend_Config(
196 'adapter' => 'Mysqli',
199 'username' => 'webuser',
200 'password' => 'secret',
206 $db = Zend_Db::factory($config->database);
212 <code>factory()</code> 메소드의 두번째 인자는 Zend_Config의 다른 오브젝트 혹은 배열의 형태입니다.
214 contain entries corresponding to adapter parameters.
215 This argument is optional, but if it is present, it takes
216 priority over any parameters supplied in the first argument.
221 <sect3 id="zend.db.adapter.connecting.parameters">
223 <title>아답터 파라메터</title>
226 아래의 리스트는 Zend_Db Adapter 클래스에서 인식하는 일반적인 파라메터들입니다.
232 <emphasis role="strong">host</emphasis>:
233 데이터 베이스 서벙의 아이피나 호스트네임의 문자열입니다. 만약 데이터 베이스와 PHP 어플리케이션이 같은 호스트 상에서 운영되고 있으면 'localhost' 혹은 '127.0.0.1'을 이용하시면 됩니다.
238 <emphasis role="strong">username</emphasis>:
239 관계형 데이터베이스 서버에 접속하기 위한 어카운트의 ID입니다.
244 <emphasis role="strong">password</emphasis>:
245 관계형 데이터베이스 서버에 인증을 위한 패스워드입니다.
250 <emphasis role="strong">dbname</emphasis>:
251 관계형 데이터베이스 서버의 인스탄스 이름입니다.
256 <emphasis role="strong">port</emphasis>:
257 관계형 데이터베이스에 따라서는 관리자가 지정한 특수한 포트로만 커녁션을 지원하기도 합니다.
258 포트 파라메터는 관계형 데이터베이스 서버로의 접속히 해당 포트로의 설정을 지원합니다.
263 <emphasis role="strong">options</emphasis>:
264 이 파라메트는 모든 Zend_Db_Adapter 클라스들의 옵션들을 배열의 형태로 지정하게 되어있습니다.
269 <emphasis role="strong">driver_options</emphasis>:
270 이 파라메터는 해당 데이터베이스에서 요구하는 추가 옵션을 배열의 형태로 입력반습니다.
271 일반적으로 이 파라메터는 PDO driver의 attributes를 설정하는데 쓰입니다.
276 <emphasis role="strong">adapterNamespace</emphasis>:
277 어댑터 클래스의 접두어가 'Zend_Db_Adapter' 이외인 경우에 어댑터 클래스의 이름을 지정하기 위해 쓰입니다. 젠드 아답터 클라스 이외의 클라스를 로드 하기 위해서 <code>factory()</code>를 이용하셨을 경우 adapterNamespace를 이용하시기 바랍니다.
282 <example id="zend.db.adapter.connecting.parameters.example1">
283 <title>Factory에 대소문자 변환 옵션 지정하기</title>
285 <code>Zend_Db::CASE_FOLDING</code>를 이용하여 대소문자 변환 옵션을 지정할수 있습니다.
286 PDO나 IBM DB2 데이터베이스 드라이버의 <code>ATTR_CASE</code>속성에 상응하는 것으로,
287 쿼리 리절트 셋의 문자 키 값을 변환합니다. 옵션 값으로는
288 <code>Zend_Db::CASE_NATURAL</code> (기본값),
289 <code>Zend_Db::CASE_UPPER</code>, 그리고
290 <code>Zend_Db::CASE_LOWER</code> 가 있습니다.
292 <programlisting role="php"><![CDATA[<?php
294 Zend_Db::CASE_FOLDING => Zend_Db::CASE_UPPER
298 'host' => '127.0.0.1',
299 'username' => 'webuser',
300 'password' => 'xxxxxxxx',
302 'options' => $options
305 $db = Zend_Db::factory('Db2', $params);]]>
309 <example id="zend.db.adapter.connecting.parameters.example2">
310 <title>팩토리에 자동 쿼팅(auto-quoting) 옵션 지정하기</title>
312 <code>Zend_Db::AUTO_QUOTE_IDENTIFIERS</code>를 이용하여 오토 쿼팅 옵션을 지정할수 있습니다.
313 해당 값이 <code>true</code>(기본값)일 경우 데이블 이름, 컬럼 이름, 그리고 알리아스등의 Adapter 오브젝트에 의해 생성되는 모든 인자들이 모두 쿼팅 됩니다. 이는 SQL 키워드나 특수문자를 포함한 식별자 사용시 유리합니다. 만약 해당 값이 <code>false</code>일 경우 식별자의 자동쿼팅은 적용 되지않습니다. 만약 쿼트를 이용해야 할경우 <code>quoteIdentifier()</code> 메소드를 이용하여 쿼팅할수 있습니다.
315 <programlisting role="php"><![CDATA[<?php
317 Zend_Db::AUTO_QUOTE_IDENTIFIERS => false
321 'host' => '127.0.0.1',
322 'username' => 'webuser',
323 'password' => 'xxxxxxxx',
325 'options' => $options
328 $db = Zend_Db::factory('Pdo_Mysql', $params);]]>
332 <example id="zend.db.adapter.connecting.parameters.example3">
333 <title>팩토리에 PDP 드라이버 옵션 지정하기</title>
334 <programlisting role="php"><![CDATA[<?php
336 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
340 'host' => '127.0.0.1',
341 'username' => 'webuser',
342 'password' => 'xxxxxxxx',
344 'driver_options' => $pdoParams
347 $db = Zend_Db::factory('Pdo_Mysql', $params);
349 echo $db->getConnection()->getAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY);]]>
355 <sect3 id="zend.db.adapter.connecting.getconnection">
356 <title>접속 지연 관리하기</title>
359 Creating an instance of an Adapter class does not immediately
360 connect to the RDBMS server. The Adapter saves the connection
361 parameters, and makes the actual connection on demand, the
362 first time you need to execute a query. This ensures that
363 creating an Adapter object is quick and inexpensive. You can
364 create an instance of an Adapter even if you are not certain
365 that you need to run any database queries during the current
366 request your application is serving.
370 If you need to force the Adapter to connect to the RDBMS, use
371 the <code>getConnection()</code> method. This method returns
372 an object for the connection as represented by the respective
373 PHP database extension. For example, if you use any of the
374 Adapter classes for PDO drivers, then
375 <code>getConnection()</code> returns the PDO object, after
376 initiating it as a live connection to the specific database.
380 It can be useful to force the connection if you want to catch
381 any exceptions it throws as a result of invalid account
382 credentials, or other failure to connect to the RDBMS server.
383 These exceptions are not thrown until the connection is made,
384 so it can help simplify your application code if you handle the
385 exceptions in one place, instead of at the time of
386 the first query against the database.
389 <example id="zend.db.adapter.connecting.getconnection.example">
390 <title>접속 예외 처리</title>
391 <programlisting role="php"><![CDATA[<?php
393 $db = Zend_Db::factory('Pdo_Mysql', $parameters);
394 $db->getConnection();
395 } catch (Zend_Db_Adapter_Exception $e) {
396 // perhaps a failed login credential, or perhaps the RDBMS is not running
397 } catch (Zend_Exception $e) {
398 // perhaps factory() failed to load the specified Adapter class
407 <sect2 id="zend.db.adapter.example-database">
409 <title>The example database</title>
412 In the documentation for Zend_Db classes, we use a set of simple
413 tables to illustrate usage of the classes and methods. These
414 example tables could store information for tracking bugs in a
415 software development project. The database contains four tables:
421 <emphasis role="strong">accounts</emphasis> stores
422 information about each user of the bug-tracking database.
427 <emphasis role="strong">products</emphasis> stores
428 information about each product for which a bug can be
434 <emphasis role="strong">bugs</emphasis> stores information
435 about bugs, including that current state of the bug, the
436 person who reported the bug, the person who is assigned to
437 fix the bug, and the person who is assigned to verify the
443 <emphasis role="strong">bugs_products</emphasis> stores a
444 relationship between bugs and products. This implements a
445 many-to-many relationship, because a given bug may be
446 relevant to multiple products, and of course a given
447 product can have multiple bugs.
453 The following SQL data definition language pseudocode describes the
454 tables in this example database. These example tables are used
455 extensively by the automated unit tests for Zend_Db.
458 <programlisting role="sql"><![CDATA[
459 CREATE TABLE accounts (
460 account_name VARCHAR(100) NOT NULL PRIMARY KEY
463 CREATE TABLE products (
464 product_id INTEGER NOT NULL PRIMARY KEY,
465 product_name VARCHAR(100)
469 bug_id INTEGER NOT NULL PRIMARY KEY,
470 bug_description VARCHAR(100),
471 bug_status VARCHAR(20),
472 reported_by VARCHAR(100) REFERENCES accounts(account_name),
473 assigned_to VARCHAR(100) REFERENCES accounts(account_name),
474 verified_by VARCHAR(100) REFERENCES accounts(account_name)
477 CREATE TABLE bugs_products (
478 bug_id INTEGER NOT NULL REFERENCES bugs,
479 product_id INTEGER NOT NULL REFERENCES products,
480 PRIMARY KEY (bug_id, product_id)
485 Also notice that the <code>bugs</code> table contains multiple
486 foreign key references to the <code>accounts</code> table.
487 Each of these foreign keys may reference a different row in the
488 <code>accounts</code> table for a given bug.
492 The diagram below illustrates the physical data model of the
497 <inlinegraphic width="387" scale="100" align="center" valign="middle"
498 fileref="figures/zend.db.adapter.example-database.png" format="PNG" />
503 <sect2 id="zend.db.adapter.select">
505 <title>Reading Query Results</title>
508 This section describes methods of the Adapter class with which you
509 can run SELECT queries and retrieve the query results.
512 <sect3 id="zend.db.adapter.select.fetchall">
514 <title>Fetching a Complete Result Set</title>
517 You can run a SQL SELECT query and retrieve its results in one
518 step using the <code>fetchAll()</code> method.
522 The first argument to this method is a string containing a
523 SELECT statement. Alternatively, the first argument can be an
524 object of class <link linkend="zend.db.select">Zend_Db_Select</link>.
525 The Adapter automatically converts this object to a string
526 representation of the SELECT statement.
530 The second argument to <code>fetchAll()</code> is an array of
531 values to substitute for parameter placeholders in the SQL
535 <example id="zend.db.adapter.select.fetchall.example">
536 <title>Using fetchAll()</title>
537 <programlisting role="php"><![CDATA[<?php
538 $sql = 'SELECT * FROM bugs WHERE bug_id = ?';
540 $result = $db->fetchAll($sql, 2);]]>
546 <sect3 id="zend.db.adapter.select.fetch-mode">
548 <title>Changing the Fetch Mode</title>
551 By default, <code>fetchAll()</code> returns an array of
552 rows, each of which is an associative array. The keys of the
553 associative array are the columns or column aliases named in
558 You can specify a different style of fetching results using the
559 <code>setFetchMode()</code> method. The modes supported are
560 identified by constants:
566 <emphasis role="strong">Zend_Db::FETCH_ASSOC</emphasis>:
567 return data in an array of associative arrays.
568 The array keys are column names, as strings.
569 This is the default fetch mode for Zend_Db_Adapter classes.
572 Note that if your select-list contains more than one
573 column with the same name, for example if they are from
574 two different tables in a JOIN, there can be only one
575 entry in the associative array for a given name.
576 If you use the FETCH_ASSOC mode, you should specify
577 column aliases in your SELECT query to ensure that the
578 names result in unique array keys.
581 By default, these strings are returned as they are
582 returned by the database driver. This is typically the
583 spelling of the column in the RDBMS server. You can
584 specify the case for these strings, using the
585 <code>Zend_Db::CASE_FOLDING</code> option.
586 Specify this when instantiating the Adapter.
587 See <xref linkend="zend.db.adapter.connecting.parameters.example1" />.
592 <emphasis role="strong">Zend_Db::FETCH_NUM</emphasis>:
593 return data in an array of arrays. The arrays are
594 indexed by integers, corresponding to the position of
595 the respective field in the select-list of the query.
600 <emphasis role="strong">Zend_Db::FETCH_BOTH</emphasis>:
601 return data in an array of arrays. The array keys are
602 both strings as used in the FETCH_ASSOC mode, and
603 integers as used in the FETCH_NUM mode. Note that the
604 number of elements in the array is double that which
605 would be in the array if you used iether FETCH_ASSOC
611 <emphasis role="strong">Zend_Db::FETCH_COLUMN</emphasis>:
612 return data in an array of values. The value in each array
613 is the value returned by one column of the result set.
614 By default, this is the first column, indexed by 0.
619 <emphasis role="strong">Zend_Db::FETCH_OBJ</emphasis>:
620 return data in an array of objects. The default class
621 is the PHP built-in class stdClass. Columns of the
622 result set are available as public properties of the
628 <example id="zend.db.adapter.select.fetch-mode.example">
629 <title>Using setFetchMode()</title>
630 <programlisting role="php"><![CDATA[<?php
631 $db->setFetchMode(Zend_Db::FETCH_OBJ);
633 $result = $db->fetchAll('SELECT * FROM bugs WHERE bug_id = ?', 2);
635 // $result is an array of objects
636 echo $result[0]->bug_description;]]>
642 <sect3 id="zend.db.adapter.select.fetchassoc">
644 <title>Fetching a Result Set as an Associative Array</title>
647 The <code>fetchAssoc()</code> method returns data in an array
648 of associative arrays, regardless of what value you have set
652 <example id="zend.db.adapter.select.fetchassoc.example">
653 <title>Using fetchAssoc()</title>
654 <programlisting role="php"><![CDATA[<?php
655 $db->setFetchMode(Zend_Db::FETCH_OBJ);
657 $result = $db->fetchAssoc('SELECT * FROM bugs WHERE bug_id = ?', 2);
659 // $result is an array of associative arrays, in spite of the fetch mode
660 echo $result[0]['bug_description'];]]>
666 <sect3 id="zend.db.adapter.select.fetchcol">
668 <title>Fetching a Single Column from a Result Set</title>
671 The <code>fetchCol()</code> method returns data in an array
672 of values, regardless of the value you have set for the fetch mode.
673 This only returns the first column returned by the query.
674 Any other columns returned by the query are discarded.
675 If you need to return a column other than the first, see <xref linkend="zend.db.statement.fetching.fetchcolumn" />.
678 <example id="zend.db.adapter.select.fetchcol.example">
679 <title>Using fetchCol()</title>
680 <programlisting role="php"><![CDATA[<?php
681 $db->setFetchMode(Zend_Db::FETCH_OBJ);
683 $result = $db->fetchCol('SELECT bug_description, bug_id FROM bugs WHERE bug_id = ?', 2);
685 // contains bug_description; bug_id is not returned
692 <sect3 id="zend.db.adapter.select.fetchpairs">
694 <title>Fetching Key-Value Pairs from a Result Set</title>
697 The <code>fetchPairs()</code> method returns data in an array
698 of key-value pairs, as an associative array with a single entry
699 per row. The key of this associative array is taken from the
700 first column returned by the SELECT query. The value is taken
701 from the second column returned by the SELECT query. Any other
702 columns returned by the query are discarded.
706 You should design the SELECT query so that the first column
707 returned has unique values. If there are duplicates values in
708 the first column, entries in the associative array will be
712 <example id="zend.db.adapter.select.fetchpairs.example">
713 <title>Using fetchPairs()</title>
714 <programlisting role="php"><![CDATA[<?php
715 $db->setFetchMode(Zend_Db::FETCH_OBJ);
717 $result = $db->fetchPairs('SELECT bug_id, bug_status FROM bugs');
724 <sect3 id="zend.db.adapter.select.fetchrow">
726 <title>Fetching a Single Row from a Result Set</title>
729 The <code>fetchRow()</code> method returns data using the
730 current fetch mode, but it returns only the first row
731 fetched from the result set.
734 <example id="zend.db.adapter.select.fetchrow.example">
735 <title>Using fetchRow()</title>
736 <programlisting role="php"><![CDATA[<?php
737 $db->setFetchMode(Zend_Db::FETCH_OBJ);
739 $result = $db->fetchRow('SELECT * FROM bugs WHERE bug_id = 2');
741 // note that $result is a single object, not an array of objects
742 echo $result->bug_description;]]>
747 <sect3 id="zend.db.adapter.select.fetchone">
749 <title>Fetching a Single Scalar from a Result Set</title>
752 The <code>fetchOne()</code> method is like a combination
753 of <code>fetchRow()</code> with <code>fetchCol()</code>,
754 in that it returns data only for the first row fetched from
755 the result set, and it returns only the value of the first
756 column in that row. Therefore it returns only a single
757 scalar value, not an array or an object.
760 <example id="zend.db.adapter.select.fetchone.example">
761 <title>Using fetchOne()</title>
762 <programlisting role="php"><![CDATA[<?php
763 $result = $db->fetchOne('SELECT bug_status FROM bugs WHERE bug_id = 2');
765 // this is a single string value
773 <sect2 id="zend.db.adapter.write">
775 <title>Writing Changes to the Database</title>
778 You can use the Adapter class to write new data or change existing
779 data in your database. This section describes methods to do these
783 <sect3 id="zend.db.adapter.write.insert">
785 <title>Inserting Data</title>
788 You can add new rows to a table in your database using the
789 <code>insert()</code> method. The first argument is a string
790 that names the table, and the second argument is an associative
791 array, mapping column names to data values.
794 <example id="zend.db.adapter.write.insert.example">
795 <title>Inserting to a table</title>
796 <programlisting role="php"><![CDATA[<?php
798 'created_on' => '2007-03-22',
799 'bug_description' => 'Something wrong',
800 'bug_status' => 'NEW'
803 $db->insert('bugs', $data);]]>
808 Columns you exclude from the array of data are not specified to
809 the database. Therefore, they follow the same rules that an
810 SQL INSERT statement follows: if the column has a DEFAULT
811 clause, the column takes that value in the row created,
812 otherwise the column is left in a NULL state.
816 By default, the values in your data array are inserted using
817 parameters. This reduces risk of some types of security
818 issues. You don't need to apply escaping or quoting to values
823 You might need values in the data array to be treated as SQL
824 expressions, in which case they should not be quoted. By
825 default, all data values passed as strings are treated as
826 string literals. To specify that the value is an SQL
827 expression and therefore should not be quoted, pass the value
828 in the data array as an object of type Zend_Db_Expr instead of
832 <example id="zend.db.adapter.write.insert.example2">
833 <title>Inserting expressions to a table</title>
834 <programlisting role="php"><![CDATA[<?php
836 'created_on' => new Zend_Db_Expr('CURDATE()'),
837 'bug_description' => 'Something wrong',
838 'bug_status' => 'NEW'
841 $db->insert('bugs', $data);]]>
847 <sect3 id="zend.db.adapter.write.lastinsertid">
849 <title>Retrieving a Generated Value</title>
852 Some RDBMS brands support auto-incrementing primary keys.
853 A table defined this way generates a primary key value
854 automatically during an INSERT of a new row. The return value
855 of the <code>insert()</code> method is <emphasis>not</emphasis>
856 the last inserted ID, because the table might not have an
857 auto-incremented column. Instead, the return value is the
858 number of rows affected (usually 1).
862 If your table is defined with an auto-incrementing primary key,
863 you can call the <code>lastInsertId()</code> method after the
864 insert. This method returns the last value generated in the
865 scope of the current database connection.
868 <example id="zend.db.adapter.write.lastinsertid.example-1">
869 <title>Using lastInsertId() for an auto-increment key</title>
870 <programlisting role="php"><![CDATA[<?php
871 $db->insert('bugs', $data);
873 // return the last value generated by an auto-increment column
874 $id = $db->lastInsertId();]]>
879 Some RDBMS brands support a sequence object, which generates
880 unique values to serve as primary key values. To support
881 sequences, the <code>lastInsertId()</code> method accepts two
882 optional string arguments. These arguments name the table and
883 the column, assuming you have followed the convention that a
884 sequence is named using the table and column names for which
885 the sequence generates values, and a suffix "_seq". This is
886 based on the convention used by PostgreSQL when naming
887 sequences for SERIAL columns. For example, a table "bugs" with
888 primary key column "bug_id" would use a sequence named
892 <example id="zend.db.adapter.write.lastinsertid.example-2">
893 <title>Using lastInsertId() for a sequence</title>
894 <programlisting role="php"><![CDATA[<?php
895 $db->insert('bugs', $data);
897 // return the last value generated by sequence 'bugs_bug_id_seq'.
898 $id = $db->lastInsertId('bugs', 'bug_id');
900 // alternatively, return the last value generated by sequence 'bugs_seq'.
901 $id = $db->lastInsertId('bugs');]]>
906 If the name of your sequence object does not follow this naming
907 convention, use the <code>lastSequenceId()</code> method
908 instead. This method takes a single string argument, naming
909 the sequence literally.
912 <example id="zend.db.adapter.write.lastinsertid.example-3">
913 <title>Using lastSequenceId()</title>
914 <programlisting role="php"><![CDATA[<?php
915 $db->insert('bugs', $data);
917 // return the last value generated by sequence 'bugs_id_gen'.
918 $id = $db->lastSequenceId('bugs_id_gen');]]>
923 For RDBMS brands that don't support sequences, including MySQL,
924 Microsoft SQL Server, and SQLite, the arguments to the
925 lastInsertId() method are ignored, and the value returned is the
926 most recent value generated for any table by INSERT operations
927 during the current connection. For these RDBMS brands, the
928 lastSequenceId() method always returns <code>null</code>.
932 <title>Why not use "SELECT MAX(id) FROM table"?</title>
934 Sometimes this query returns the most recent primary key
935 value inserted into the table. However, this technique
936 is not safe to use in an environment where multiple clients are
937 inserting records to the database. It is possible, and
938 therefore is bound to happen eventually, that another
939 client inserts another row in the instant between the
940 insert performed by your client application and your query
941 for the MAX(id) value. Thus the value returned does not
942 identify the row you inserted, it identifies the row
943 inserted by some other client. There is no way to know
944 when this has happened.
947 Using a strong transaction isolation mode such as
948 "repeatable read" can mitigate this risk, but some RDBMS
949 brands don't support the transaction isolation required for
950 this, or else your application may use a lower transaction
951 isolation mode by design.
954 Furthermore, using an expression like "MAX(id)+1" to generate
955 a new value for a primary key is not safe, because two clients
956 could do this query simultaneously, and then both use the same
957 calculated value for their next INSERT operation.
960 All RDBMS brands provide mechanisms to generate unique
961 values, and to return the last value generated. These
962 mechanisms necessarily work outside of the scope of
963 transaction isolation, so there is no chance of two clients
964 generating the same value, and there is no chance that the
965 value generated by another client could be reported to your
966 client's connection as the last value generated.
972 <sect3 id="zend.db.adapter.write.update">
973 <title>Updating Data</title>
976 You can update rows in a database table using the
977 <code>update()</code> method of an Adapter. This method takes
978 three arguments: the first is the name of the table; the
979 second is an associative array mapping columns to change to new
980 values to assign to these columns.
984 The values in the data array are treated as string literals.
985 See <xref linkend="zend.db.adapter.write.insert" />
986 for information on using SQL expressions in the data array.
990 The third argument is a string containing an SQL expression
991 that is used as criteria for the rows to change. The values
992 and identifiers in this argument are not quoted or escaped.
993 You are responsible for ensuring that any dynamic content is
994 interpolated into this string safely.
995 See <xref linkend="zend.db.adapter.quoting" />
996 for methods to help you do this.
1000 The return value is the number of rows affected by the update
1004 <example id="zend.db.adapter.write.update.example">
1005 <title>Updating rows</title>
1006 <programlisting role="php"><![CDATA[<?php
1008 'updated_on' => '2007-03-23',
1009 'bug_status' => 'FIXED'
1012 $n = $db->update('bugs', $data, 'bug_id = 2');]]>
1017 If you omit the third argument, then all rows in the database
1018 table are updated with the values specified in the data array.
1022 If you provide an array of strings as the third argument, these
1023 strings are joined together as terms in an expression separated
1024 by <code>AND</code> operators.
1027 <example id="zend.db.adapter.write.update.example-array">
1028 <title>Updating rows using an array of expressions</title>
1029 <programlisting role="php"><![CDATA[<?php
1031 'updated_on' => '2007-03-23',
1032 'bug_status' => 'FIXED'
1035 $where[] = "reported_by = 'goofy'";
1036 $where[] = "bug_status = 'OPEN'";
1038 $n = $db->update('bugs', $data, $where);
1040 // Resulting SQL is:
1041 // UPDATE "bugs" SET "update_on" = '2007-03-23', "bug_status" = 'FIXED'
1042 // WHERE ("reported_by" = 'goofy') AND ("bug_status" = 'OPEN')]]>
1048 <sect3 id="zend.db.adapter.write.delete">
1049 <title>Deleting Data</title>
1051 You can delete rows from a database table using the
1052 <code>delete()</code> method. This method takes two arguments:
1053 the first is a string naming the table.
1057 The second argument is a string containing an SQL expression
1058 that is used as criteria for the rows to delete. The values
1059 and identifiers in this argument are not quoted or escaped.
1060 You are responsible for ensuring that any dynamic content is
1061 interpolated into this string safely.
1062 See <xref linkend="zend.db.adapter.quoting" />
1063 for methods to help you do this.
1067 The return value is the number of rows affected by the delete
1071 <example id="zend.db.adapter.write.delete.example">
1072 <title>Deleting rows</title>
1073 <programlisting role="php"><![CDATA[<?php
1074 $n = $db->delete('bugs', 'bug_id = 3');]]>
1079 If you omit the second argument, the result is that all rows in
1080 the database table are deleted.
1084 If you provide an array of strings as the second argument, these
1085 strings are joined together as terms in an expression separated
1086 by <code>AND</code> operators.
1093 <sect2 id="zend.db.adapter.quoting">
1095 <title>Quoting Values and Identifiers</title>
1098 When you form SQL queries, often it is the case that you need to
1099 include the values of PHP variables in SQL expressions. This is
1100 risky, because if the value in a PHP string contains certain
1101 symbols, such as the quote symbol, it could result in invalid SQL.
1102 For example, notice the imbalanced quote characters in the
1104 <programlisting role="php"><![CDATA[
1106 $sql = "SELECT * FROM bugs WHERE reported_by = '$name'";
1109 // SELECT * FROM bugs WHERE reported_by = 'O'Reilly']]>
1114 Even worse is the risk that such code mistakes might be exploited
1115 deliberately by a person who is trying to manipulate the function
1116 of your web application. If they can specify the value of a PHP
1117 variable through the use of an HTTP parameter or other mechanism,
1118 they might be able to make your SQL queries do things that you
1119 didn't intend them to do, such as return data to which the person
1120 should not have privilege to read. This is a serious and widespread
1121 technique for violating application security, known as "SQL Injection"
1122 (see <ulink url="http://en.wikipedia.org/wiki/SQL_Injection">http://en.wikipedia.org/wiki/SQL_Injection</ulink>).
1126 The Zend_Db Adapter class provides convenient functions to help you
1127 reduce vulnerabilities to SQL Injection attacks in your PHP code.
1128 The solution is to escape special characters such as quotes in PHP
1129 values before they are interpolated into your SQL strings.
1130 This protects against both accidental and deliberate manipulation
1131 of SQL strings by PHP variables that contain special characters.
1134 <sect3 id="zend.db.adapter.quoting.quote">
1136 <title>Using <code>quote()</code></title>
1139 The <code>quote()</code> method accepts a single argument, a
1140 scalar string value. It returns the value with special
1141 characters escaped in a manner appropriate for the RDBMS you
1142 are using, and surrounded by string value delimiters. The
1143 standard SQL string value delimiter is the single-quote
1147 <example id="zend.db.adapter.quoting.quote.example">
1148 <title>Using quote()</title>
1149 <programlisting role="php"><![CDATA[<?php
1150 $name = $db->quote("O'Reilly");
1154 $sql = "SELECT * FROM bugs WHERE reported_by = $name";
1157 // SELECT * FROM bugs WHERE reported_by = 'O\'Reilly']]>
1162 Note that the return value of <code>quote()</code> includes the
1163 quote delimiters around the string. This is different from
1164 some functions that escape special characters but do not add
1165 the quote delimiters, for example
1166 <ulink url="http://www.php.net/mysqli_real_escape_string">mysql_real_escape_string()</ulink>.
1170 Values may need to be quoted or not quoted according to the SQL
1171 datatype context in which they are used. For instance, in some
1172 RDBMS brands, an integer value must not be quoted as a string
1173 if it is compared to an integer-type column or expression.
1174 In other words, the following is an error in some SQL
1175 implementations, assuming <code>intColumn</code> has a SQL
1176 datatype of <code>INTEGER</code>
1178 <programlisting role="php"><![CDATA[
1179 SELECT * FROM atable WHERE intColumn = '123']]>
1184 You can use the optional second argument to the
1185 <code>quote()</code> method to apply quoting selectively for
1186 the SQL datatype you specify.
1189 <example id="zend.db.adapter.quoting.quote.example-2">
1190 <title>Using quote() with a SQL type</title>
1191 <programlisting role="php"><![CDATA[<?php
1193 $sql = 'SELECT * FROM atable WHERE intColumn = '
1194 . $db->quoteType($value, 'INTEGER');
1200 Each Zend_Db_Adapter class has encoded the names of numeric
1201 SQL datatypes for the respective brand of RDBMS. You can also
1202 use the constants <code>Zend_Db::INT_TYPE</code>,
1203 <code>Zend_Db::BIGINT_TYPE</code>, and
1204 <code>Zend_Db::FLOAT_TYPE</code> to write code in a more
1205 RDBMS-independent way.
1209 Zend_Db_Table specifies SQL types to <code>quote()</code>
1210 automatically when generating SQL queries that reference a
1211 table's key columns.
1216 <sect3 id="zend.db.adapter.quoting.quote-into">
1218 <title>Using <code>quoteInto()</code></title>
1221 The most typical usage of quoting is to interpolate a PHP
1222 variable into a SQL expression or statement. You can use the
1223 <code>quoteInto()</code> method to do this in one step. This
1224 method takes two arguments: the first argument is a string
1225 containing a placeholder symbol (<code>?</code>), and the
1226 second argument is a value or PHP variable that should be
1227 substituted for that placeholder.
1231 The placeholder symbol is the same symbol used by many RDBMS
1232 brands for positional parameters, but the
1233 <code>quoteInto()</code> method only emulates query parameters.
1234 The method simply interpolates the value into the string,
1235 escapes special characters, and applies quotes around it.
1236 True query parameters maintain the separation between the SQL
1237 string and the parameters as the statement is parsed in the
1241 <example id="zend.db.adapter.quoting.quote-into.example">
1242 <title>Using quoteInto()</title>
1243 <programlisting role="php"><![CDATA[<?php
1244 $sql = $db->quoteInto("SELECT * FROM bugs WHERE reported_by = ?", "O'Reilly");
1247 // SELECT * FROM bugs WHERE reported_by = 'O\'Reilly']]>
1252 You can use the optional third parameter of
1253 <code>quoteInto()</code> to specify the SQL datatype. Numeric
1254 datatypes are not quoted, and other types are quoted.
1257 <example id="zend.db.adapter.quoting.quote-into.example-2">
1258 <title>Using quoteInto() with a SQL type</title>
1259 <programlisting role="php"><![CDATA[<?php
1260 $sql = $db->quoteInto("SELECT * FROM bugs WHERE bug_id = ?", '1234', 'INTEGER');
1263 // SELECT * FROM bugs WHERE reported_by = 1234]]>
1268 <sect3 id="zend.db.adapter.quoting.quote-identifier">
1270 <title>Using <code>quoteIdentifier()</code></title>
1273 Values are not the only part of SQL syntax that might need to
1274 be variable. If you use PHP variables to name tables, columns,
1275 or other identifiers in your SQL statements, you might need to
1276 quote these strings too. By default, SQL identifiers have
1277 syntax rules like PHP and most other programming languages.
1278 For example, identifiers should not contain spaces, certain
1279 punctuation or special characters, or international characters.
1280 Also certain words are reserved for SQL syntax, and should not
1281 be used as identifiers.
1285 However, SQL has a feature called <emphasis>delimited identifiers</emphasis>,
1286 which allows broader choices for the spelling of identifiers.
1287 If you enclose a SQL identifier in the proper types of quotes,
1288 you can use identifiers with spellings that would be invalid
1289 without the quotes. Delimited identifiers can contain spaces,
1290 punctuation, or international characters. You can also use SQL
1291 reserved words if you enclose them in identifier delimiters.
1295 The <code>quoteIdentifier()</code> method works like
1296 <code>quote()</code>, but it applies the identifier delimiter
1297 characters to the string according to the type of Adapter you
1298 use. For example, standard SQL uses double-quotes
1299 (<code>"</code>) for identifier delimiters, and most RDBMS
1300 brands use that symbol. MySQL uses back-quotes
1301 (<code>`</code>) by default. The
1302 <code>quoteIdentifier()</code> method also escapes special
1303 characters within the string argument.
1306 <example id="zend.db.adapter.quoting.quote-identifier.example">
1307 <title>Using quoteIdentifier()</title>
1308 <programlisting role="php"><![CDATA[<?php
1309 // we might have a table name that is an SQL reserved word
1310 $tableName = $db->quoteIdentifier("order");
1312 $sql = "SELECT * FROM $tableName";
1315 // SELECT * FROM "order"]]>
1320 SQL delimited identifiers are case-sensitive, unlike unquoted
1321 identifiers. Therefore, if you use delimited identifiers, you
1322 must use the spelling of the identifier exactly as it is stored
1323 in your schema, including the case of the letters.
1327 In most cases where SQL is generated within Zend_Db classes,
1328 the default is that all identifiers are delimited
1329 automatically. You can change this behavior with the option
1330 <code>Zend_Db::AUTO_QUOTE_IDENTIFIERS</code>. Specify this
1331 when instantiating the Adapter.
1332 See <xref linkend="zend.db.adapter.connecting.parameters.example2" />.
1339 <sect2 id="zend.db.adapter.transactions">
1341 <title>Controlling Database Transactions</title>
1344 Databases define transactions as logical units of work that can be
1345 committed or rolled back as a single change, even if they operate
1346 on multiple tables. All queries to a database are executed within
1347 the context of a transaction, even if the database driver manages
1348 them implicitly. This is called <emphasis>auto-commit</emphasis>
1349 mode, in which the database driver creates a transaction for every
1350 statement you execute, and commits that transaction after your
1351 SQL statement has been executed. By default, all Zend_Db Adapter
1352 classes operate in auto-commit mode.
1356 Alternatively, you can specify the beginning and resolution of a
1357 transaction, and thus control how many SQL queries are included in
1358 a single group that is committed (or rolled back) as a single
1359 operation. Use the <code>beginTransaction()</code> method to
1360 initiate a transaction. Subsequent SQL statements are executed in
1361 the context of the same transaction until you resolve it
1366 To resolve the transaction, use either the <code>commit()</code> or
1367 <code>rollBack()</code> methods. The <code>commit()</code> method
1368 marks changes made during your transaction as committed, which
1369 means the effects of these changes are shown in queries run in
1374 The <code>rollBack()</code> method does the opposite: it discards
1375 the changes made during your transaction. The changes are
1376 effectively undone, and the state of the data returns to how it was
1377 before you began your transaction. However, rolling back your
1378 transaction has no effect on changes made by other transactions
1379 running concurrently.
1383 After you resolve this transaction, <code>Zend_Db_Adapter</code>
1384 returns to auto-commit mode until you call
1385 <code>beginTransaction()</code> again.
1388 <example id="zend.db.adapter.transactions.example">
1389 <title>Managing a transaction to ensure consistency</title>
1390 <programlisting role="php"><![CDATA[<?php
1391 // Start a transaction explicitly.
1392 $db->beginTransaction();
1395 // Attempt to execute one or more queries:
1400 // If all succeed, commit the transaction and all changes
1401 // are committed at once.
1404 } catch (Exception $e) {
1405 // If any of the queries failed and threw an exception,
1406 // we want to roll back the whole transaction, reversing
1407 // changes made in the transaction, even those that succeeded.
1408 // Thus all changes are committed together, or none are.
1410 echo $e->getMessage();
1417 <sect2 id="zend.db.adapter.list-describe">
1419 <title>Listing and Describing Tables</title>
1422 The <code>listTables()</code> method returns an array of strings,
1423 naming all tables in the current database.
1427 The <code>describeTable()</code> method returns an associative
1428 array of metadata about a table. Specify the name of the table
1429 as a string in the first argument to this method. The second
1430 argument is optional, and names the schema in which the table
1435 The keys of the associative array returned are the column names of
1436 the table. The value corresponding to each column is also an
1437 associative array, with the following keys and values:
1440 <table frame="all" cellpadding="5" id="zend.db.adapter.list-describe.metadata">
1441 <title>Metadata fields returned by describeTable()</title>
1442 <tgroup cols="3" align="left" colsep="1" rowsep="1">
1447 <entry>Description</entry>
1452 <entry>SCHEMA_NAME</entry>
1453 <entry>(string)</entry>
1454 <entry>Name of the database schema in which this table exists.</entry>
1457 <entry>TABLE_NAME</entry>
1458 <entry>(string)</entry>
1459 <entry>Name of the table to which this column belongs.</entry>
1462 <entry>COLUMN_NAME</entry>
1463 <entry>(string)</entry>
1464 <entry>Name of the column.</entry>
1467 <entry>COLUMN_POSITION</entry>
1468 <entry>(integer)</entry>
1469 <entry>Ordinal position of the column in the table.</entry>
1472 <entry>DATA_TYPE</entry>
1473 <entry>(string)</entry>
1474 <entry>RDBMS name of the datatype of the column.</entry>
1477 <entry>DEFAULT</entry>
1478 <entry>(string)</entry>
1479 <entry>Default value for the column, if any.</entry>
1482 <entry>NULLABLE</entry>
1483 <entry>(boolean)</entry>
1484 <entry>True if the column accepts SQL NULLs, false if the column has a NOT NULL constraint.</entry>
1487 <entry>LENGTH</entry>
1488 <entry>(integer)</entry>
1489 <entry>Length or size of the column as reported by the RDBMS.</entry>
1492 <entry>SCALE</entry>
1493 <entry>(integer)</entry>
1494 <entry>Scale of SQL NUMERIC or DECIMAL type.</entry>
1497 <entry>PRECISION</entry>
1498 <entry>(integer)</entry>
1499 <entry>Precision of SQL NUMERIC or DECIMAL type.</entry>
1502 <entry>UNSIGNED</entry>
1503 <entry>(boolean)</entry>
1504 <entry>True if an integer-based type is reported as UNSIGNED.</entry>
1507 <entry>PRIMARY</entry>
1508 <entry>(boolean)</entry>
1509 <entry>True if the column is part of the primary key of this table.</entry>
1512 <entry>PRIMARY_POSITION</entry>
1513 <entry>(integer)</entry>
1514 <entry>Ordinal position (1-based) of the column in the primary key.</entry>
1517 <entry>IDENTITY</entry>
1518 <entry>(boolean)</entry>
1519 <entry>True if the column uses an auto-generated value.</entry>
1526 If no table exists matching the table name and optional schema name
1527 specified, then <code>describeTable()</code> returns an empty array.
1532 <sect2 id="zend.db.adapter.closing">
1534 <title>Closing a Connection</title>
1537 Normally it is not necessary to close a database connection. PHP
1538 automatically cleans up all resources and the end of a request.
1539 Database extensions are designed to close the connection as the
1540 reference to the resource object is cleaned up.
1544 However, if you have a long-duration PHP script that initiates many
1545 database connections, you might need to close the connection, to avoid
1546 exhausting the capacity of your RDBMS server. You can use the
1547 Adapter's <code>closeConnection()</code> method to explicitly close
1548 the underlying database connection.
1551 <example id="zend.db.adapter.closing.example">
1552 <title>Closing a database connection</title>
1553 <programlisting role="php"><![CDATA[<?php
1554 $db->closeConnection();]]>
1559 <title>Does Zend_Db support persistent connections?</title>
1561 The usage of persistent connections is not supported
1562 or encouraged in Zend_Db.
1565 Using persistent connections can cause an excess of idle
1566 connections on the RDBMS server, which causes more problems
1567 than any performance gain you might achieve by reducing the
1568 overhead of making connections.
1571 Database connections have state. That is, some objects in the
1572 RDBMS server exist in session scope. Examples are locks, user
1573 variables, temporary tables, and information about the most
1574 recently executed query, such as rows affected, and last
1575 generated id value. If you use persistent connections, your
1576 application could access invalid or privileged data that were
1577 created in a previous PHP request.
1583 <sect2 id="zend.db.adapter.other-statements">
1585 <title>Running Other Database Statements</title>
1588 There might be cases in which you need to access the connection
1589 object directly, as provided by the PHP database extension. Some
1590 of these extensions may offer features that are not surfaced by
1591 methods of Zend_Db_Adapter_Abstract.
1595 For example, all SQL statements run by Zend_Db are prepared, then
1596 executed. However, some database features are incompatible with
1597 prepared statements. DDL statements like CREATE and ALTER cannot
1598 be prepared in MySQL. Also, SQL statements don't benefit
1599 from the <ulink url="http://dev.mysql.com/doc/refman/5.1/en/query-cache-how.html">MySQL Query Cache</ulink>,
1600 prior to MySQL 5.1.17.
1604 Most PHP database extensions provide a method to execute SQL
1605 statements without preparing them. For example, in PDO, this
1606 method is <code>exec()</code>. You can access the connection
1607 object in the PHP extension directly using getConnection().
1610 <example id="zend.db.adapter.other-statements.example">
1611 <title>Running a non-prepared statement in a PDO adapter</title>
1612 <programlisting role="php"><![CDATA[<?php
1613 $result = $db->getConnection()->exec('DROP TABLE bugs');]]>
1618 Similarly, you can access other methods or properties that are
1619 specific to PHP database extensions. Be aware, though, that by
1620 doing this you might constrain your application to the interface
1621 provided by the extension for a specific brand of RDBMS.
1625 In future versions of Zend_Db, there will be opportunities to
1626 add method entry points for functionality that is common to
1627 the supported PHP database extensions. This will not affect
1628 backward compatibility.
1633 <sect2 id="zend.db.adapter.adapter-notes">
1635 <title>Notes on Specific Adapters</title>
1638 This section lists differences between the Adapter classes of which
1639 you should be aware.
1642 <sect3 id="zend.db.adapter.adapter-notes.ibm-db2">
1643 <title>IBM DB2</title>
1647 Specify this Adapter to the factory() method with the
1653 This Adapter uses the PHP extension ibm_db2.
1658 IBM DB2 supports both sequences and auto-incrementing
1659 keys. Therefore the arguments to
1660 <code>lastInsertId()</code> are optional. If you give
1661 no arguments, the Adapter returns the last value
1662 generated for an auto-increment key. If you give
1663 arguments, the Adapter returns the last value generated
1664 by the sequence named according to the convention
1665 '<emphasis>table</emphasis>_<emphasis>column</emphasis>_seq'.
1671 <sect3 id="zend.db.adapter.adapter-notes.mysqli">
1672 <title>MySQLi</title>
1676 Specify this Adapter to the <code>factory()</code>
1677 method with the name 'Mysqli'.
1682 This Adapter utilizes the PHP extension mysqli.
1687 MySQL does not support sequences, so
1688 <code>lastInsertId()</code> ignores its arguments and
1689 always returns the last value generated for an
1690 auto-increment key. The <code>lastSequenceId()</code>
1691 method returns <code>null</code>.
1697 <sect3 id="zend.db.adapter.adapter-notes.oracle">
1698 <title>Oracle</title>
1702 Specify this Adapter to the <code>factory()</code>
1703 method with the name 'Oracle'.
1708 This Adapter uses the PHP extension oci8.
1713 Oracle does not support auto-incrementing keys, so you
1714 should specify the name of a sequence to
1715 <code>lastInsertId()</code> or
1716 <code>lastSequenceId()</code>.
1721 The Oracle extension does not support positional
1722 parameters. You must use named parameters.
1727 Currently the <code>Zend_Db::CASE_FOLDING</code> option
1728 is not supported by the Oracle adapter. To use this
1729 option with Oracle, you must use the PDO OCI adapter.
1735 <sect3 id="zend.db.adapter.adapter-notes.pdo-mssql">
1736 <title>PDO Microsoft SQL Server</title>
1740 Specify this Adapter to the <code>factory()</code>
1741 method with the name 'Pdo_Mssql'.
1746 This Adapter uses the PHP extensions pdo and pdo_mssql.
1751 Microsoft SQL Server does not support sequences, so
1752 <code>lastInsertId()</code> ignores its arguments and
1753 always returns the last value generated for an
1754 auto-increment key. The <code>lastSequenceId()</code>
1755 method returns <code>null</code>.
1760 Zend_Db_Adapter_Pdo_Mssql sets <code>QUOTED_IDENTIFIER ON</code>
1761 immediately after connecting to a SQL Server database.
1762 This makes the driver use the standard SQL identifier
1763 delimiter symbol (<code>"</code>) instead of the
1764 proprietary square-brackets syntax SQL Server uses for
1765 delimiting identifiers.
1770 You can specify <code>pdoType</code> as a key in the
1771 options array. The value can be "mssql" (the default),
1772 "dblib", "freetds", or "sybase". This option affects
1773 the DSN prefix the adapter uses when constructing the
1774 DSN string. Both "freetds" and "sybase" imply a prefix
1775 of "sybase:", which is used for the
1776 <ulink url="http://www.freetds.org/">FreeTDS</ulink> set
1779 <ulink url="http://www.php.net/manual/en/ref.pdo-dblib.connection.php">
1780 http://www.php.net/manual/en/ref.pdo-dblib.connection.php</ulink>
1781 for more information on the DSN prefixes used in this driver.
1787 <sect3 id="zend.db.adapter.adapter-notes.pdo-mysql">
1788 <title>PDO MySQL</title>
1792 Specify this Adapter to the <code>factory()</code>
1793 method with the name 'Pdo_Mysql'.
1798 This Adapter uses the PHP extensions pdo and pdo_mysql.
1803 MySQL does not support sequences, so
1804 <code>lastInsertId()</code> ignores its arguments and
1805 always returns the last value generated for an
1806 auto-increment key. The <code>lastSequenceId()</code>
1807 method returns <code>null</code>.
1813 <sect3 id="zend.db.adapter.adapter-notes.pdo-oci">
1814 <title>PDO Oracle</title>
1818 Specify this Adapter to the <code>factory()</code>
1819 method with the name 'Pdo_Oci'.
1824 This Adapter uses the PHP extensions pdo and pdo_oci.
1829 Oracle does not support auto-incrementing keys, so you
1830 should specify the name of a sequence to
1831 <code>lastInsertId()</code> or
1832 <code>lastSequenceId()</code>.
1838 <sect3 id="zend.db.adapter.adapter-notes.pdo-pgsql">
1839 <title>PDO PostgreSQL</title>
1843 Specify this Adapter to the <code>factory()</code>
1844 method with the name 'Pdo_Pgsql'.
1849 This Adapter uses the PHP extensions pdo and pdo_pgsql.
1854 PostgreSQL supports both sequences and auto-incrementing
1855 keys. Therefore the arguments to
1856 <code>lastInsertId()</code> are optional. If you give
1857 no arguments, the Adapter returns the last value
1858 generated for an auto-increment key. If you give
1859 arguments, the Adapter returns the last value generated
1860 by the sequence named according to the convention
1861 '<emphasis>table</emphasis>_<emphasis>column</emphasis>_seq'.
1867 <sect3 id="zend.db.adapter.adapter-notes.pdo-sqlite">
1868 <title>PDO SQLite</title>
1872 Specify this Adapter to the <code>factory()</code>
1873 method with the name 'Pdo_Sqlite'.
1878 This Adapter uses the PHP extensions pdo and pdo_sqlite.
1883 SQLite does not support sequences, so
1884 <code>lastInsertId()</code> ignores its arguments and
1885 always returns the last value generated for an
1886 auto-increment key. The <code>lastSequenceId()</code>
1887 method returns <code>null</code>.
1892 To connect to an SQLite2 database, specify
1893 <code>'dsnprefix'=>'sqlite2'</code> in the array of
1894 parameters when creating an instance of the
1900 To connect to an in-memory SQLite database,
1901 specify <code>'dbname'=>':memory:'</code> in the
1902 array of parameters when creating an instance of
1903 the Pdo_Sqlite Adapter.
1908 Older versions of the SQLite driver for PHP do not seem
1909 to support the PRAGMA commands necessary to ensure that
1910 short column names are used in result sets. If you
1911 have problems that your result sets are returned with
1912 keys of the form "tablename.columnname" when you do a
1913 join query, then you should upgrade to the current