Zend_Db_AdapterZend_Db and its related classes provide a simple SQL database interface for Zend Framework. The Zend_Db_Adapter is the basic class you use to connect your PHP application to an RDBMS. There is a different Adapter class for each brand of RDBMS. The Zend_Db adapters create a bridge from the vendor-specific PHP extensions to a common interface to help you write PHP applications once and deploy with multiple brands of RDBMS with very little effort. The interface of the adapter class is similar to the interface of the » PHP Data Objects extension. Zend_Db provides Adapter classes to PDO drivers for the following RDBMS brands:
In addition, Zend_Db provides Adapter classes that utilize PHP database extensions for the following RDBMS brands:
Connecting to a Database Using an AdapterThis section describes how to create an instance of a database Adapter. This corresponds to making a connection to your RDBMS server from your PHP application. Using a Zend_Db Adapter ConstructorYou can create an instance of an adapter using its constructor. An adapter constructor takes one argument, which is an array of parameters used to declare the connection. Example #1 Using an Adapter Constructor
Using the Zend_Db FactoryAs an alternative to using an adapter constructor directly, you can create an instance of an adapter using the static method Zend_Db::factory(). This method dynamically loads the adapter class file on demand using Zend_Loader::loadClass(). The first argument is a string that names the base name of the adapter class. For example the string 'Pdo_Mysql' corresponds to the class Zend_Db_Adapter_Pdo_Mysql. The second argument is the same array of parameters you would have given to the adapter constructor. Example #2 Using the Adapter Factory Method
If you create your own class that extends Zend_Db_Adapter_Abstract, but you do not name your class with the "Zend_Db_Adapter" package prefix, you can use the factory() method to load your adapter if you specify the leading portion of the adapter class with the 'adapterNamespace' key in the parameters array. Example #3 Using the Adapter Factory Method for a Custom Adapter Class
Using Zend_Config with the Zend_Db FactoryOptionally, you may specify either argument of the factory() method as an object of type Zend_Config. If the first argument is a config object, it is expected to contain a property named adapter, containing the string naming the adapter class name base. Optionally, the object may contain a property named params, with subproperties corresponding to adapter parameter names. This is used only if the second argument of the factory() method is absent. Example #4 Using the Adapter Factory Method with a Zend_Config Object In the example below, a Zend_Config object is created from an array. You can also load data from an external file using classes such as Zend_Config_Ini and Zend_Config_Xml.
The second argument of the factory() method may be an associative array containing entries corresponding to adapter parameters. This argument is optional. If the first argument is of type Zend_Config, it is assumed to contain all parameters, and the second argument is ignored. Adapter ParametersThe following list explains common parameters recognized by Zend_Db Adapter classes.
Example #5 Passing the Case-Folding Option to the Factory You can specify this option by the constant Zend_Db::CASE_FOLDING. This corresponds to the ATTR_CASE attribute in PDO and IBM DB2 database drivers, adjusting the case of string keys in query result sets. The option takes values Zend_Db::CASE_NATURAL (the default), Zend_Db::CASE_UPPER, and Zend_Db::CASE_LOWER.
Example #6 Passing the Auto-Quoting Option to the Factory You can specify this option by the constant Zend_Db::AUTO_QUOTE_IDENTIFIERS. If the value is TRUE (the default), identifiers like table names, column names, and even aliases are delimited in all SQL syntax generated by the Adapter object. This makes it simple to use identifiers that contain SQL keywords, or special characters. If the value is FALSE, identifiers are not delimited automatically. If you need to delimit identifiers, you must do so yourself using the quoteIdentifier() method.
Example #7 Passing PDO Driver Options to the Factory
Example #8 Passing Serialization Options to the Factory
Managing Lazy ConnectionsCreating an instance of an Adapter class does not immediately connect to the RDBMS server. The Adapter saves the connection parameters, and makes the actual connection on demand, the first time you need to execute a query. This ensures that creating an Adapter object is quick and inexpensive. You can create an instance of an Adapter even if you are not certain that you need to run any database queries during the current request your application is serving. If you need to force the Adapter to connect to the RDBMS, use the getConnection() method. This method returns an object for the connection as represented by the respective PHP database extension. For example, if you use any of the Adapter classes for PDO drivers, then getConnection() returns the PDO object, after initiating it as a live connection to the specific database. It can be useful to force the connection if you want to catch any exceptions it throws as a result of invalid account credentials, or other failure to connect to the RDBMS server. These exceptions are not thrown until the connection is made, so it can help simplify your application code if you handle the exceptions in one place, instead of at the time of the first query against the database. Additionally, an adapter can get serialized to store it, for example, in a session variable. This can be very useful not only for the adapter itself, but for other objects that aggregate it, like a Zend_Db_Select object. By default, adapters are allowed to be serialized, if you don't want it, you should consider passing the Zend_Db::ALLOW_SERIALIZATION option with FALSE, see the example above. To respect lazy connections principle, the adapter won't reconnect itself after being unserialized. You must then call getConnection() yourself. You can make the adapter auto-reconnect by passing the Zend_Db::AUTO_RECONNECT_ON_UNSERIALIZE with TRUE as an adapter option. Example #9 Handling Connection Exceptions
Example DatabaseIn the documentation for Zend_Db classes, we use a set of simple tables to illustrate usage of the classes and methods. These example tables could store information for tracking bugs in a software development project. The database contains four tables:
The following SQL data definition language pseudocode describes the tables in this example database. These example tables are used extensively by the automated unit tests for Zend_Db. Also notice that the 'bugs' table contains multiple foreign key references to the 'accounts' table. Each of these foreign keys may reference a different row in the 'accounts' table for a given bug. The diagram below illustrates the physical data model of the example database.
Reading Query ResultsThis section describes methods of the Adapter class with which you can run SELECT queries and retrieve the query results. Fetching a Complete Result SetYou can run a SQL SELECT query and retrieve its results in one step using the fetchAll() method. The first argument to this method is a string containing a SELECT statement. Alternatively, the first argument can be an object of class Zend_Db_Select. The Adapter automatically converts this object to a string representation of the SELECT statement. The second argument to fetchAll() is an array of values to substitute for parameter placeholders in the SQL statement. Example #10 Using fetchAll()
Changing the Fetch ModeBy default, fetchAll() returns an array of rows, each of which is an associative array. The keys of the associative array are the columns or column aliases named in the select query. You can specify a different style of fetching results using the setFetchMode() method. The modes supported are identified by constants:
Example #11 Using setFetchMode()
Fetching a Result Set as an Associative ArrayThe fetchAssoc() method returns data in an array of associative arrays, regardless of what value you have set for the fetch mode, using the first column as the array index. Example #12 Using fetchAssoc()
Fetching a Single Column from a Result SetThe fetchCol() method returns data in an array of values, regardless of the value you have set for the fetch mode. This only returns the first column returned by the query. Any other columns returned by the query are discarded. If you need to return a column other than the first, see this section. Example #13 Using fetchCol()
Fetching Key-Value Pairs from a Result SetThe fetchPairs() method returns data in an array of key-value pairs, as an associative array with a single entry per row. The key of this associative array is taken from the first column returned by the SELECT query. The value is taken from the second column returned by the SELECT query. Any other columns returned by the query are discarded. You should design the SELECT query so that the first column returned has unique values. If there are duplicates values in the first column, entries in the associative array will be overwritten. Example #14 Using fetchPairs()
Fetching a Single Row from a Result SetThe fetchRow() method returns data using the current fetch mode, but it returns only the first row fetched from the result set. Example #15 Using fetchRow()
Fetching a Single Scalar from a Result SetThe fetchOne() method is like a combination of fetchRow() with fetchCol(), in that it returns data only for the first row fetched from the result set, and it returns only the value of the first column in that row. Therefore it returns only a single scalar value, not an array or an object. Example #16 Using fetchOne()
Writing Changes to the DatabaseYou can use the Adapter class to write new data or change existing data in your database. This section describes methods to do these operations. Inserting DataYou can add new rows to a table in your database using the insert() method. The first argument is a string that names the table, and the second argument is an associative array, mapping column names to data values. Example #17 Inserting in a Table
Columns you exclude from the array of data are not specified to the database. Therefore, they follow the same rules that an SQL INSERT statement follows: if the column has a DEFAULT clause, the column takes that value in the row created, otherwise the column is left in a NULL state. By default, the values in your data array are inserted using parameters. This reduces risk of some types of security issues. You don't need to apply escaping or quoting to values in the data array. You might need values in the data array to be treated as SQL expressions, in which case they should not be quoted. By default, all data values passed as strings are treated as string literals. To specify that the value is an SQL expression and therefore should not be quoted, pass the value in the data array as an object of type Zend_Db_Expr instead of a plain string. Example #18 Inserting Expressions in a Table
Retrieving a Generated ValueSome RDBMS brands support auto-incrementing primary keys. A table defined this way generates a primary key value automatically during an INSERT of a new row. The return value of the insert() method is not the last inserted ID, because the table might not have an auto-incremented column. Instead, the return value is the number of rows affected (usually 1). If your table is defined with an auto-incrementing primary key, you can call the lastInsertId() method after the insert. This method returns the last value generated in the scope of the current database connection. Example #19 Using lastInsertId() for an Auto-Increment Key
Some RDBMS brands support a sequence object, which generates unique values to serve as primary key values. To support sequences, the lastInsertId() method accepts two optional string arguments. These arguments name the table and the column, assuming you have followed the convention that a sequence is named using the table and column names for which the sequence generates values, and a suffix "_seq". This is based on the convention used by PostgreSQL when naming sequences for SERIAL columns. For example, a table "bugs" with primary key column "bug_id" would use a sequence named "bugs_bug_id_seq". Example #20 Using lastInsertId() for a Sequence
If the name of your sequence object does not follow this naming convention, use the lastSequenceId() method instead. This method takes a single string argument, naming the sequence literally. Example #21 Using lastSequenceId()
For RDBMS brands that don't support sequences, including MariaDB, MySQL, Microsoft SQL Server, and SQLite, the arguments to the lastInsertId() method are ignored, and the value returned is the most recent value generated for any table by INSERT operations during the current connection. For these RDBMS brands, the lastSequenceId() method always returns NULL.
Updating DataYou can update rows in a database table using the update() method of an Adapter. This method takes three arguments: the first is the name of the table; the second is an associative array mapping columns to change to new values to assign to these columns. The values in the data array are treated as string literals. See this section for information on using SQL expressions in the data array. The third argument is a string containing an SQL expression that is used as criteria for the rows to change. The values and identifiers in this argument are not quoted or escaped. You are responsible for ensuring that any dynamic content is interpolated into this string safely. See this section for methods to help you do this. The return value is the number of rows affected by the update operation. Example #22 Updating Rows
If you omit the third argument, then all rows in the database table are updated with the values specified in the data array. If you provide an array of strings as the third argument, these strings are joined together as terms in an expression separated by AND operators. If you provide an array of arrays as the third argument, the values will be automatically quoted into the keys. These will then be joined together as terms, separated by AND operators. Example #23 Updating Rows Using an Array of Expressions
Example #24 Updating Rows Using an Array of Arrays
Deleting DataYou can delete rows from a database table using the delete() method. This method takes two arguments: the first is a string naming the table. The second argument is a string containing an SQL expression that is used as criteria for the rows to delete. The values and identifiers in this argument are not quoted or escaped. You are responsible for ensuring that any dynamic content is interpolated into this string safely. See this section for methods to help you do this. The return value is the number of rows affected by the delete operation. Example #25 Deleting Rows
If you omit the second argument, the result is that all rows in the database table are deleted. If you provide an array of strings as the second argument, these strings are joined together as terms in an expression separated by AND operators. If you provide an array of arrays as the second argument, the values will be automatically quoted into the keys. These will then be joined together as terms, separated by AND operators. Quoting Values and IdentifiersWhen you form SQL queries, often it is the case that you need to include the values of PHP variables in SQL expressions. This is risky, because if the value in a PHP string contains certain symbols, such as the quote symbol, it could result in invalid SQL. For example, notice the imbalanced quote characters in the following query:
Even worse is the risk that such code mistakes might be exploited deliberately by a person who is trying to manipulate the function of your web application. If they can specify the value of a PHP variable through the use of an HTTP parameter or other mechanism, they might be able to make your SQL queries do things that you didn't intend them to do, such as return data to which the person should not have privilege to read. This is a serious and widespread technique for violating application security, known as "SQL Injection" (see » http://en.wikipedia.org/wiki/SQL_Injection). The Zend_Db Adapter class provides convenient functions to help you reduce vulnerabilities to SQL Injection attacks in your PHP code. The solution is to escape special characters such as quotes in PHP values before they are interpolated into your SQL strings. This protects against both accidental and deliberate manipulation of SQL strings by PHP variables that contain special characters. Using quote()The quote() method accepts a single argument, a scalar string value. It returns the value with special characters escaped in a manner appropriate for the RDBMS you are using, and surrounded by string value delimiters. The standard SQL string value delimiter is the single-quote ('). Example #26 Using quote()
Note that the return value of quote() includes the quote delimiters around the string. This is different from some functions that escape special characters but do not add the quote delimiters, for example » mysql_real_escape_string(). Values may need to be quoted or not quoted according to the SQL datatype context in which they are used. For instance, in some RDBMS brands, an integer value must not be quoted as a string if it is compared to an integer-type column or expression. In other words, the following is an error in some SQL implementations, assuming intColumn has a SQL datatype of INTEGER
You can use the optional second argument to the quote() method to apply quoting selectively for the SQL datatype you specify. Example #27 Using quote() with a SQL Type
Each Zend_Db_Adapter class has encoded the names of numeric SQL datatypes for the respective brand of RDBMS. You can also use the constants Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, and Zend_Db::FLOAT_TYPE to write code in a more RDBMS-independent way. Zend_Db_Table specifies SQL types to quote() automatically when generating SQL queries that reference a table's key columns. Using quoteInto()The most typical usage of quoting is to interpolate a PHP variable into a SQL expression or statement. You can use the quoteInto() method to do this in one step. This method takes two arguments: the first argument is a string containing a placeholder symbol (?), and the second argument is a value or PHP variable that should be substituted for that placeholder. The placeholder symbol is the same symbol used by many RDBMS brands for positional parameters, but the quoteInto() method only emulates query parameters. The method simply interpolates the value into the string, escapes special characters, and applies quotes around it. True query parameters maintain the separation between the SQL string and the parameters as the statement is parsed in the RDBMS server. Example #28 Using quoteInto()
You can use the optional third parameter of quoteInto() to specify the SQL datatype. Numeric datatypes are not quoted, and other types are quoted. Example #29 Using quoteInto() with a SQL Type
Using quoteIdentifier()Values are not the only part of SQL syntax that might need to be variable. If you use PHP variables to name tables, columns, or other identifiers in your SQL statements, you might need to quote these strings too. By default, SQL identifiers have syntax rules like PHP and most other programming languages. For example, identifiers should not contain spaces, certain punctuation or special characters, or international characters. Also certain words are reserved for SQL syntax, and should not be used as identifiers. However, SQL has a feature called delimited identifiers, which allows broader choices for the spelling of identifiers. If you enclose a SQL identifier in the proper types of quotes, you can use identifiers with spellings that would be invalid without the quotes. Delimited identifiers can contain spaces, punctuation, or international characters. You can also use SQL reserved words if you enclose them in identifier delimiters. The quoteIdentifier() method works like quote(), but it applies the identifier delimiter characters to the string according to the type of Adapter you use. For example, standard SQL uses double-quotes (") for identifier delimiters, and most RDBMS brands use that symbol. MySQL uses back-quotes (`) by default. The quoteIdentifier() method also escapes special characters within the string argument. Example #30 Using quoteIdentifier()
SQL delimited identifiers are case-sensitive, unlike unquoted identifiers. Therefore, if you use delimited identifiers, you must use the spelling of the identifier exactly as it is stored in your schema, including the case of the letters. In most cases where SQL is generated within Zend_Db classes, the default is that all identifiers are delimited automatically. You can change this behavior with the option Zend_Db::AUTO_QUOTE_IDENTIFIERS. Specify this when instantiating the Adapter. See this example. Controlling Database TransactionsDatabases define transactions as logical units of work that can be committed or rolled back as a single change, even if they operate on multiple tables. All queries to a database are executed within the context of a transaction, even if the database driver manages them implicitly. This is called auto-commit mode, in which the database driver creates a transaction for every statement you execute, and commits that transaction after your SQL statement has been executed. By default, all Zend_Db Adapter classes operate in auto-commit mode. Alternatively, you can specify the beginning and resolution of a transaction, and thus control how many SQL queries are included in a single group that is committed (or rolled back) as a single operation. Use the beginTransaction() method to initiate a transaction. Subsequent SQL statements are executed in the context of the same transaction until you resolve it explicitly. To resolve the transaction, use either the commit() or rollBack() methods. The commit() method marks changes made during your transaction as committed, which means the effects of these changes are shown in queries run in other transactions. The rollBack() method does the opposite: it discards the changes made during your transaction. The changes are effectively undone, and the state of the data returns to how it was before you began your transaction. However, rolling back your transaction has no effect on changes made by other transactions running concurrently. After you resolve this transaction, Zend_Db_Adapter returns to auto-commit mode until you call beginTransaction() again. Example #31 Managing a Transaction to Ensure Consistency
Listing and Describing TablesThe listTables() method returns an array of strings, naming all tables in the current database. The describeTable() method returns an associative array of metadata about a table. Specify the name of the table as a string in the first argument to this method. The second argument is optional, and names the schema in which the table exists. The keys of the associative array returned are the column names of the table. The value corresponding to each column is also an associative array, with the following keys and values:
If no table exists matching the table name and optional schema name specified, then describeTable() returns an empty array. Closing a ConnectionNormally it is not necessary to close a database connection. PHP automatically cleans up all resources and the end of a request. Database extensions are designed to close the connection as the reference to the resource object is cleaned up. However, if you have a long-duration PHP script that initiates many database connections, you might need to close the connection, to avoid exhausting the capacity of your RDBMS server. You can use the Adapter's closeConnection() method to explicitly close the underlying database connection. Since release 1.7.2, you could check you are currently connected to the RDBMS server with the method isConnected(). This means that a connection resource has been initiated and wasn't closed. This function is not currently able to test for example a server side closing of the connection. This is internally use to close the connection. It allow you to close the connection multiple times without errors. It was already the case before 1.7.2 for PDO adapters but not for the others. Example #32 Closing a Database Connection
|