Search code examples
phpzend-frameworkzend-db

Zend_Db without Zend Framework


I want using Zend_Db without Zend_Framework. I want incorporate Zend_Db for my existing website that was not made using Zend Framework. Is it possible to use Zend_Db like this? Can you recommend good tutorial or example how to do it good?


Solution

  • To some extent, this depends upon the web framework you are using. But, in general, the Zend_Db documentation is pretty clear in this regard.

    Create an adapter instance in your bootstrap. As an example:

    $db = Zend_Db::factory('Pdo_Mysql', array(
        'host'     => '127.0.0.1',
        'username' => 'webuser',
        'password' => 'xxxxxxxx',
        'dbname'   => 'test'
    ));
    

    If you plan to use Zend_Db_Table, then you can make this the default adapter:

    Zend_Db_Table::setDefaultAdapter($db);
    

    In any case, it's helpful to have this adapter saved someplace where you can access it. For example:

    Zend_Registry::set('db', $db);
    

    Then in your downstream code, use this adapter to create queries for select(), insert(), update(), delete(), etc:

    $db = Zend_Registry::get('db');
    $select = $db->select()
        ->from('posts')
        ->where('cat_id = ?', $catId)
        ->order('date_posted DESC')
        ->limit(5);
    $rows = $db->fetchAll($select);
    

    Hope this helps. Cheers!