Zend_Db_Statement

In addition to convenient methods such as fetchAll() and insert() documented in Zend_Db_Adapter, you can use a statement object to gain more options for running queries and fetching result sets. This section describes how to get an instance of a statement object, and how to use its methods.

Zend_Db_Statement is based on the PDOStatement object in the » PHP Data Objects extension.

Creating a Statement

Typically, a statement object is returned by the query() method of the database Adapter class. This method is a general way to prepare any SQL statement. The first argument is a string containing an SQL statement. The optional second argument is an array of values to bind to parameter placeholders in the SQL string.

Example #1 Creating a SQL statement object with query()

  1. $stmt = $db->query(
  2.             'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?',
  3.             array('goofy', 'FIXED')
  4.         );

The statement object corresponds to a SQL statement that has been prepared, and executed once with the bind-values specified. If the statement was a SELECT query or other type of statement that returns a result set, it is now ready to fetch results.

You can create a statement with its constructor, but this is less typical usage. There is no factory method to create this object, so you need to load the specific statement class and call its constructor. Pass the Adapter object as the first argument, and a string containing an SQL statement as the second argument. The statement is prepared, but not executed.

Example #2 Using a SQL statement constructor

  1. $sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
  2.  
  3. $stmt = new Zend_Db_Statement_Mysqli($db, $sql);

Executing a Statement

You need to execute a statement object if you create it using its constructor, or if you want to execute the same statement multiple times. Use the execute() method of the statement object. The single argument is an array of value to bind to parameter placeholders in the statement.

If you use positional parameters, or those that are marked with a question mark symbol ('?'), pass the bind values in a plain array.

Example #3 Executing a statement with positional parameters

  1. $sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
  2.  
  3. $stmt = new Zend_Db_Statement_Mysqli($db, $sql);
  4.  
  5. $stmt->execute(array('goofy', 'FIXED'));

If you use named parameters, or those that are indicated by a string identifier preceded by a colon character (':'), pass the bind values in an associative array. The keys of this array should match the parameter names.

Example #4 Executing a statement with named parameters

  1. $sql = 'SELECT * FROM bugs WHERE ' .
  2.        'reported_by = :reporter AND bug_status = :status';
  3.  
  4. $stmt = new Zend_Db_Statement_Mysqli($db, $sql);
  5.  
  6. $stmt->execute(array(':reporter' => 'goofy', ':status' => 'FIXED'));

PDO statements support both positional parameters and named parameters, but not both types in a single SQL statement. Some of the Zend_Db_Statement classes for non-PDO extensions may support only one type of parameter or the other.

Fetching Results from a SELECT Statement

You can call methods on the statement object to retrieve rows from SQL statements that produce result set. SELECT, SHOW, DESCRIBE and EXPLAIN are examples of statements that produce a result set. INSERT, UPDATE, and DELETE are examples of statements that don't produce a result set. You can execute the latter SQL statements using Zend_Db_Statement, but you cannot call methods to fetch rows of results from them.

Fetching a Single Row from a Result Set

To retrieve one row from the result set, use the fetch() method of the statement object. All three arguments of this method are optional:

  • Fetch style is the first argument. This controls the structure in which the row is returned. See this chapter for a description of the valid values and the corresponding data formats.

  • Cursor orientation is the second argument. The default is Zend_Db::FETCH_ORI_NEXT, which simply means that each call to fetch() returns the next row in the result set, in the order returned by the RDBMS.

  • Offset is the third argument. If the cursor orientation is Zend_Db::FETCH_ORI_ABS, then the offset number is the ordinal number of the row to return. If the cursor orientation is Zend_Db::FETCH_ORI_REL, then the offset number is relative to the cursor position before fetch() was called.

fetch() returns FALSE if all rows of the result set have been fetched.

Example #5 Using fetch() in a loop

  1. $stmt = $db->query('SELECT * FROM bugs');
  2.  
  3. while ($row = $stmt->fetch()) {
  4.     echo $row['bug_description'];
  5. }

See also » PDOStatement::fetch().

Fetching a Complete Result Set

To retrieve all the rows of the result set in one step, use the fetchAll() method. This is equivalent to calling the fetch() method in a loop and returning all the rows in an array. The fetchAll() method accepts two arguments. The first is the fetch style, as described above, and the second indicates the number of the column to return, when the fetch style is Zend_Db::FETCH_COLUMN.

Example #6 Using fetchAll()

  1. $stmt = $db->query('SELECT * FROM bugs');
  2.  
  3. $rows = $stmt->fetchAll();
  4.  
  5. echo $rows[0]['bug_description'];

See also » PDOStatement::fetchAll().

Changing the Fetch Mode

By default, the statement object returns rows of the result set as associative arrays, mapping column names to column values. You can specify a different format for the statement class to return rows, just as you can in the Adapter class. You can use the setFetchMode() method of the statement object to specify the fetch mode. Specify the fetch mode using Zend_Db class constants FETCH_ASSOC, FETCH_NUM, FETCH_BOTH, FETCH_COLUMN, and FETCH_OBJ. See this chapter for more information on these modes. Subsequent calls to the statement methods fetch() or fetchAll() use the fetch mode that you specify.

Example #7 Setting the fetch mode

  1. $stmt = $db->query('SELECT * FROM bugs');
  2.  
  3. $stmt->setFetchMode(Zend_Db::FETCH_NUM);
  4.  
  5. $rows = $stmt->fetchAll();
  6.  
  7. echo $rows[0][0];

See also » PDOStatement::setFetchMode().

Fetching a Single Column from a Result Set

To return a single column from the next row of the result set, use fetchColumn(). The optional argument is the integer index of the column, and it defaults to 0. This method returns a scalar value, or FALSE if all rows of the result set have been fetched.

Note this method operates differently than the fetchCol() method of the Adapter class. The fetchColumn() method of a statement returns a single value from one row. The fetchCol() method of an adapter returns an array of values, taken from the first column of all rows of the result set.

Example #8 Using fetchColumn()

  1. $stmt = $db->query('SELECT bug_id, bug_description, bug_status FROM bugs');
  2.  
  3. $bug_status = $stmt->fetchColumn(2);

See also » PDOStatement::fetchColumn().

Fetching a Row as an Object

To retrieve a row from the result set structured as an object, use the fetchObject(). This method takes two optional arguments. The first argument is a string that names the class name of the object to return; the default is 'stdClass'. The second argument is an array of values that will be passed to the constructor of that class.

Example #9 Using fetchObject()

  1. $stmt = $db->query('SELECT bug_id, bug_description, bug_status FROM bugs');
  2.  
  3. $obj = $stmt->fetchObject();
  4.  
  5. echo $obj->bug_description;

See also » PDOStatement::fetchObject().

blog comments powered by Disqus