views:

331

answers:

2

Hi,

I'm currently using the Zend_Db class to manage my database connections. I had a few questions about it.

  • Does it manage opening connections smartly? (eg, I have a connection already open, does it know to take use of it - or do I have to constantly check if theres' already an open connection before I open a new one?)
  • I use the following code to fetch results (fetching in FETCH_OBJ mode):

     $final = $result->fetchAll();

    return $final[0]->first_name;

for some reason, fetchRow doesn't work - so I constantly use fetchAll, even when I'll only have one result (like searching WHERE id= number and id is a PK)

My question is - how much more time/memory am I sacrificing when I use fetchAll and not fetchRow, even when there's only result?

  • I've created the following class to manage my connections:

    require 'Zend/Db.php';

  class dbconnect extends Zend_Db 

 {



 function init ()
    {
         $params = array (......

        return Zend_Db::factory ( 'PDO_MYSQL', $params );   
    }

 }

and then I call


$handle = dbconnect::init

$handle->select()....

is this the best way? does anyone have a better idea?

Thanks!

p.s. I'm sorry the code formatting came out sloppy here..

+1  A: 

Lots of questions!

Does it manage opening connections smartly?

Yes, when you run your first query, a connection is created, and subsequent queries use the same connection. This is true if you're reusing the same Zend_Db adapter. I usually make it available to my entire application using Zend_Registry:

$db = Zend_Db::factory(...) // create Db instance
Zend_Registry::set('db', $db);

//in another class or file somewhere
$db = Zend_Registry::get('db');
$db->query(...)//run a query

The above code usually goes in your application boostrap. I wouldn't bother to extend the Zend_Db class just to initialise and instance of it.

Regarding fetchRow - I believe the key difference is that the query run is limited to 1 row, and the object returned is a Zend_Db_Table_Row rather than a Zend_Db_Table_Rowset (like an array of rows), and does not perform significantly slower.

fetchRow should be fine so post some code that's not working as there's probably a mistake somewhere.

David Caunt
A: 

addition to dcaunt's answer: FetchAll returns array OR Zend_Db_Talbe_Rowset - depending on if you execute $zendDbTableModel->fetchAll() or $dbAdapter->fetchAll() Same goes for fetchRow(). If you fail to make fetchRow working for models, it's easier to use $model->getAdapter()->fetchRow($sqlString);

Tomáš Fejfar