Since I have had quite a bit of traffic to my site from people searching 'Yii MySQL', 'Yii Framework MySQL' 'Connecting Yii To MySQL' and others I figured I'd accommodate you guys with a quick 'How-to' series. This is part one and simply covers getting your MySQL connection working using Yii.
Lets get started...
Before being able to use MySQL properly in Yii you must have the MySQL PDO extension installed.
After doing that you have to snap-in the MySQL connector into your configuration file.
Assuming you started your Yii application using the command-line tool you should have a file in protected/config/main.php.
<?php //File: protected/config/main.php // uncomment the following to define a path alias // Yii::setPathOfAlias('local','path/to/local-folder'); // This is the main Web application configuration. Any writable // CWebApplication properties can be configured here. return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>'PHP/MySQL Development', 'defaultController'=>'post', // preloading 'log' component 'preload'=>array('log'), // autoloading model and component classes 'import'=>array( 'application.models.*', 'application.components.*', ), // application-level parameters that can be accessed // using Yii::app()->params['paramName'] 'params'=>require(dirname(__FILE__).'/params.php'), // application components 'components'=>array( 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), ), ), 'user'=>array( // enable cookie-based authentication 'allowAutoLogin'=>true, // force 401 HTTP error if authentication needed 'loginUrl'=>null, ), 'db'=>array( 'class'=>'CDbConnection', 'connectionString'=>'mysql:host=myDatabaseHost;dbname=myDatabasename', 'username' => 'myUsername', 'password' => 'myPassword' ), 'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( 'tag/<tag>'=>'post/list', 'posts'=>'post/list', 'post/<id:\d+>'=>'post/show', 'post/update/<id:\d+>'=>'post/update', ), ), 'cache'=>array( 'class'=>'system.caching.CDbCache', ), ), );
Now I left most of my configuration in here just to show you where the DB configuration is at in relative terms to whatever else you may have. So just copy the 'db' array, change the parameters to what you use for your mySQL and you should be ready for the next step!

7 comments to "Yii Framework + MySQL Part 1 - Connecting To MySQL"
Leave a Comment