Archive

Posts Tagged ‘application.ini’

Using Zend_Db_Select without specifying a database adapter

March 7th, 2010 Alvos No comments

I’ve been working with the Zend_Db_Table object when I want to get one or multiple records from a database table by using fetchAll() or find() methods. The latest versions of Zend Framework – I’m currently using 1.10.2 – come with the following warning: “The API for fetch operations has been superseded to allow a Zend_Db_Table_Select object to modify the query. However, the deprecated usage of the fetchRow() and fetchAll() methods will continue to work without modification.”

The warning says that the deprecated usage of both methods will continue to work without modification but as I’ve had bad times when I’ve trusted these “promises” because deprecated features usually become unmaintained and eventually disappear, I strongly recommend to modify your code to use the latest features offered.

If you follow this link you’ll find how to use the Zend_Db_Select object and in all the examples you need to create and instance of the Zend_Db object in order to use the select object, as in the following example:

1
2
$db = Zend_Db::factory( ...options... );
$select = new Zend_Db_Select($db);

The problem is that most of us never actually create an instance of the Zend_Db object and I don’t recommend it since it’s not configurable at all. As powerful as Zend Framework is, the zf tool it provides, allows us to create database connections that can be used globally and are configurable through the application.ini file. In case you don’t know how to do that here’s an example of how to create a connection to a MySQL database:

How to create a database connection using zf tool

How to create a database connection using zf tool

If you didn’t understand the code in the image you might need to go through the quick start again.

After you have created a database connection using the zf tool, you will be able to use it globally so here’s an example of how to use Zend_Db_Select without having to create an instance of the Zend_Db object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public function testDBSelect($value)
{
 $select = $this->getDbTable()->select()->from('tbl_example')->where('field = ?', $value);
  
 $stmt = $select->query();
 $result = $stmt->fetchAll();
  
 if (0 == count($result))
 {
  return;
 }
  
 $row = $result[0];
  
 echo($row['Field1']);
 echo($row['Field2']);
}

Basically, you get the instance of the Zend_Db_Select from a Zend_Db_Table object.  The results from the select come in the form of a matrix where the rows are  the records gotten from the table and the columns are the field values  per row.

You would only need to go through the results variable using a basic cycle and access the field values like a normal array $row['field1'], $row['field2'], etc.

Well, for all the ones not being able to solve this problem, there you go.

Cheers!