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?
问题:
回答1:
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!
回答2:
For Zend Framework 2.*, creating the adapter would be:
$db = new \Zend\Db\Adapter\Adapter([
'driver' => 'Pdo_Mysql',
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxx',
'database' => 'test',
]);
To create select:
$sql = new \Zend\Db\Sql\Sql($db);
$select = $sql->select()
->from('posts')
->where(array('cat_id' => $catId))
->order('date_posted DESC')
->limit(5);
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
Or, if you want to get pure SQL from the $select:
$selectSql = $sql->getSqlStringForSqlObject($select);
Docs might be helpful. It can be even simpler if TableGateway is used.
回答3:
Using Zend_Db would even be preferable (IMHO) over using Raw PDO. Just create a $db Object and then create SQL Statements using Zend_Db_Select Class and pass the $select SQL Statement to the fetch* (fetchRow, fetchAll...) Methods.