CDbException: CDbConnection failed to open the DB connection.

Hi i have installed yii and i am doing the Yii book "Agile with Yii 1.1 and PHP5: The TrackStar Application" and setting up the phpunit and selenium tests.

I manage to setup a database and get and set data throught the models however when trying to test the database it doesnt work?!

DbTest.php


<?php

class DbTest extends CTestCase

{

    public function testConnection()

    {


        $this->assertNotEquals(NULL, Yii::app()->db);

    }

}

this gives me:


DbTest::testConnection()

CDbException: CDbConnection failed to open the DB connection.

...../framework/db/CDbConnection.php:275

...../framework/db/CDbConnection.php:242

...../framework/db/CDbConnection.php:221

...../framework/base/CModule.php:363

...../framework/base/CModule.php:86

...../YII/trackstar/protected/tests/unit/DbTest.php:10

i have also setup the bootstrap and the xml configuration to use the relevant files in the trackstar application.

this is my main.php config




/*


		'db'=>array(

			'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',

		),

 */

            

		// uncomment the following to use a MySQL database

		

		'db'=>array(

                        //'class'=>'CDbConnection',

			'connectionString' => 'mysql:host=localhost;dbname=yii_trackstar_dev',

			'emulatePrepare' => true,

			'username' => 'root',

			'password' => 'root',

			'charset' => 'utf8',

		),

note that i have disabled the sqlite. and also note that if i desable mysql and use sqlite the test runs with success…this is making me crazy since the application is clearly working with CRUD its only the tests that are failing…

please help me with this.

I think this is since i am using MAMP on my osx installation and Yii is trying to access the old PHP installation on the mac when running tests… how can i force to use the current MAMP mysql connection?

as the error says it cannot connect to the database… .so it’s something with mysql…

have you checked the Yii requirements…

PDO for mysql installed (most probably is this one) ?

can you connect to mysql by using username/password as root/root?

requirements check

PDO is installed and i can connect in a separate php file

yes root/root is correct

also note that my application is using the application in the CRUD view thus it is working, only place it is not working is in my unit tests…

Config for unit tests is usually different from the one used in the main application. Can you check that the same credentials are used?

are you referring to the test.php in the same directory as main.php?

I have tried using the same credentials there without luck…




<?php


return CMap::mergeArray(

	require(dirname(__FILE__).'/main.php'),

	array(

		'components'=>array(

			'fixture'=>array(

				'class'=>'system.test.CDbFixtureManager',

			),

                      

                         'db'=>array(

                            'connectionString' => 'mysql:host=localhost;dbname=yii_trackstar_dev',

                            'emulatePrepare' => true,

                            'username' => 'root',

                            'password' => 'root',

                            'charset' => 'utf8',

                        ),

		),

	)

);




i am suspecting my upgrade to MAMP pro has made my php system retarded, i am having issues installing xdebug as well and i bet if i had that it could help me right know…what setup are you using? MAMP or maybe linux? perhaps a virtual image with linux as PHP test server?

or are there any other ways of testing what is wrong?

You need to find log files and check for errors. Both Yii log files (protected/runtime) and PHP/Apache ones.

there are no errors in either of them concerning this issue. How can i force it?

I am having the same issue. I just can not pass the error. :(

yeah me too. i ended up creating unit test on another machine.

One difference is that phpunit is run from command line, have you checked the PHP configuration for CLI ?

Run php --ini (from command line) to get the location of the configuration file, and take a look there if all needed extensions are enabled

phpunit is not working properly from command line either. it seems the php ini is looking for it in /etc , however i am using a MAMP pro installation, how do i direct to it?

this line worked for me:


'connectionString' => 'mysql:host=127.0.0.1;dbname=trackstar_dev;port=8889;',

I am using MAMP standard version on snow leopard.

still giving the same error…maybe phpunit is trying another MYSQL socket? how do i find out which one?

ok let me tell you what i know.

i just installed snow leopard.

in the terminal i installed through already installed pear, phpunit.

here my class:


<?php


class DbTest extends CTestCase {

	public function testConnection() {

		$this->assertNotEquals(NULL, Yii::app()->db);

	}

}

I saw you are having troubles on line 10!? please let me see your protected/config/maon.php and your DbTest class. plz with all lines.

then put the exact terminal command here also. i am gonna help you through this, cause i was fighting hard too.

also please make shure of which settings you do really have with mamp.

thanks! finally :)

my MAMP config can be found here: http://stackoverflow.com/questions/4232084/phpunit-xdebug-codecoverage-not-working-in-console-mac-mamp-1-9-pro

protected/config/main.php


<?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'=>'My Web Application',


	// preloading 'log' component

	'preload'=>array('log'),


	// autoloading model and component classes

	'import'=>array(

		'application.models.*',

		'application.components.*',

	),


        'modules'=>array(

                'gii'=>array(

                    'class'=>'system.gii.GiiModule', 'password'=>'1234qwer',

                ),

        ),

	// application components

	'components'=>array(

		'user'=>array(

			// enable cookie-based authentication

			'allowAutoLogin'=>true,

		),

               

		// uncomment the following to enable URLs in path-format

		/*

		'urlManager'=>array(

			'urlFormat'=>'path',

			'rules'=>array(

				'<controller:\w+>/<id:\d+>'=>'<controller>/view',

				'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',

				'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',

			),

		),

		*/


                'db'=>array(

                        //'class'=>'CDbConnection',

			'connectionString' => 'mysql:host=localhost;dbname=yii_trackstar_dev;port=8889;',

			'emulatePrepare' => true,

			'username' => 'root',

			'password' => 'root',

			'charset' => 'utf8',

		),

            /*

		'db'=>array(

			'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',

		),

              */

            

		// uncomment the following to use a MySQL database

		

		

                

                

            

		'errorHandler'=>array(

			// use 'site/error' action to display errors

            'errorAction'=>'site/error',

        ),

		'log'=>array(

			'class'=>'CLogRouter',

			'routes'=>array(

				array(

					'class'=>'CFileLogRoute',

					'levels'=>'error, warning',

				),

				// uncomment the following to show log messages on web pages

				/*

				array(

					'class'=>'CWebLogRoute',

				),

				*/

			),

		),

	),


	// application-level parameters that can be accessed

	// using Yii::app()->params['paramName']

	'params'=>array(

		// this is used in contact page

		'adminEmail'=>'test@test.no',

	),

);

protected/config/test.php


<?php


return CMap::mergeArray(

	require(dirname(__FILE__).'/main.php'),

	array(

		'components'=>array(

			'fixture'=>array(

				'class'=>'system.test.CDbFixtureManager',

			),

                      

                         'db'=>array(

                            'connectionString' => 'mysql:host=localhost;dbname=yii_trackstar_dev;port=8889;',

                            'emulatePrepare' => true,

                            'username' => 'root',

                            'password' => 'root',

                            'charset' => 'utf8',

                        ),

		),

	)

);



DbTest.php


<?php

class DbTest extends CTestCase

{

    /*

     * Test if we have database driver active

     */

    public function testConnection()

    {

        

        $this->assertNotEquals(NULL, Yii::app()->db);

    }

}

Spent a good time to find a solution. Here it is:

‘connectionString’ => ‘mysql:host=localhost;dbname=trackstar;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock’

it will work (or change the mysql.sock to the path that you’re running)

Hello everyone,

you don’t need to specify the unix socket. Just use “localhost” instead of the IP as host, this will do the trick.

So the following line is absolutely enough to make it work:

‘connectionString’ => ‘mysql:host=localhost;dbname=trackstar_dev;’,

Explanation:

MAMP by default doesn’t allow TCP connections. You can either turn it on or use sockets. Using “localhost” is actually like using a socket.

(later I might be allowed to post a link here, for now just search it on stackoverflow)

Here a snippet from the mysql documentation

(Again, you have to search it yourself, sorry!)

"On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option."

Hope this helps,

Cheers,

Peter

I have the same problem… and I am running lampp under Ubuntu, and I get the same error , can someone fix this?

ryznar.wordpress.com/2010/06/ :rolleyes:

‘db’ => array(

        'connectionString' =&gt; [i][b]'mysql:dbname=yii_trackstar_dev;host=localhost; '[/b][/i], <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />  


         …

),