Database config

Hello. I have set the database configuration in protected/config/main.php:



<?php


return array(


	'db'=>array(


		'class'=>'CDbConnection',


		'connectionString'=>'mysql:host=127.0.0.1;dbname=<myDb>',


		'username'=>'<dbUser>','password'=>'<dbPasswd>',


But I can't figure out how to call CDbConnection without passing a connectionString. I can't just run 'new CDbConnection' because Yii complains that connectionString can't be empty. Why doesn't Yii just read it from the config file?

Help?

Is Yii::app()->db that you are looking for?

Perhaps. Can you point me to a doc that shows me how to use it? For example, just trying to guess, would the following be valid code:



<?php


Yii::app()->db->setActive(true);


$Stmt = Yii::app()->db->getPdoInstance()->prepare($sql);


$Stmt->setFetchMode(PDO::FETCH_CLASS, 'SomeClass');


$Stmt->execute($params);


while ($row = $Stmt->fetch(PDO::FETCH_CLASS)) {


	if ($row) array_push($result,$row);


}


If I can access the PDO instance from Yii::app()->db so I can use PDO::FETCH_CLASS that should be all I need.

The following page talks about how to use CDbConnection.

Unless you have very special needs, you should not access the PDO instance directly.

My only special needs are:

  1. To use PDO::FETCH_CLASS

  2. When using prepared statements, I want to provide the parameters as an array. You'll notice in my sample code that I used:

<?php $stmt->execute($params);

The second item is more of a strong preference than a requirement. I want to have a generic class for DB access that accepts a query string and an uncertain number of parameters. But thinking about it a bit more, I could do without that.

As for PDO::FETCH_CLASS, I use it because it allows me to run the result set through a constructor and get objects with methods. I don't use this a lot right now. Currently the ony thing the constructor does is concatenate the 'firstname' and 'surname' fields into a single 'name' property. But I was thinking that having the return set be a bunch of objects could come in handy later, if I want to add methods to those objects.

Anyways, looking at the DAO page on the guide, I could not see how to get the above two features.

With your requirements as described, yes, your code should be fine.