Using a Zend_Db Database connection
I'm trying to teach myself the Zend Framework. I have some extensive experience using custom-frameworks but have never used Zend. It's like trying to use a knife and fork with mittens on.
I've got a system up and running. A database connection is being created in the applition.ini file without errors.
The point I'm at is trying to use this connection to the database to execute basic SQL. The application.ini has the lines:
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.username = cpanel_dbuser
db.params.password = 123456
db.params.dbname = cpanel_dbname
I'm trying to connect to the database in my /public/index.php
$config = new Zend_Config_Ini(APPLICATION开发者_Python百科_PATH .
'/configs/application.ini', 'production');
$application->db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);
The error I get is:
Fatal error: Uncaught exception 'Zend_Db_Exception' with message 'Adapter name must be specified in a string' in /home/path/library/Zend/Db.php:226
Stack trace:
#0 /home/path/public/index.php(32): Zend_Db::factory(Array)
#1 {main} thrown in /home/path/library/Zend/Db.php on line 226
And if I print_r the Config Object
Zend_Config Object
(
[_allowModifications:protected] =>
[_index:protected] => 0
[_count:protected] => 2
[_data:protected] => Array
(
[adapter] => PDO_MYSQL
/* ... more stuff ... */
From my understanding of the tutorials & PDF's I'm working from, if I get this connection working I'll be able to do such fantastical amazements as the following from within a controller's indexAction
$data = $this->db->fetchAll(‘SELECT * FROM table’);
foreach ($data as $row) {
echo $row[‘table_fieldname’];
}
And then start writing models for the tables I have.
At this point, there's a pretty serious temptation to cut-the-corner and do this the way I already know how, but that completely defeats the purpose of learning to work within the framework.
Can anyone bridge the gap for me (or point me to a resource that can clear this up)?
In application.ini file inside config directory do
resources.db.adapter = PDO_MYSQL
resources.db.isDefaultAdapter = true
resources.db.params.host = localhost
resources.db.params.username = username
resources.db.params.password = pwd
resources.db.params.dbname = mydatabase
and whenever/wherever you need $db just do
$db = Zend_Db_Table::getDefaultAdapter()
this is the best way to do it.
public function ActionnameAction()
{
$params=array(
'host' =>'localhost',
'username' =>'username',
'password' =>'password',
'dbname' =>'database_name');
$db = Zend_Db::Factory('PDO_MYSQL',$params);
$sql="select * from table_name";
$result=$db->fetchAll($sql);
}
If I don't remember wrong, the adapters are case sensitive. You should use Pdo_Mysql
. The exception you are receiving doesn't seems to be related to this though.
精彩评论