Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter PDO database driver not working

I'm trying to use the PDO MySQL driver in my CodeIgniter application. This is my database config:

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'testdatabase';
$db['default']['dbdriver'] = 'pdo';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

However, I'm getting this error when I load a controller:

Fatal error: Uncaught exception 'PDOException' with message 'invalid data source name' in C:\xampp\htdocs\testsite\system\database\drivers\pdo\pdo_driver.php:114

I've checked the data source using die($this->hostname); in pdo_driver.php and it's coming out as:

localhost;dbname=testdatabase

so it is getting the correct database name. The database exists and I do have MySQL running.

What could be going wrong here? Thank you.

like image 773
James Dawson Avatar asked Jun 15 '12 16:06

James Dawson


3 Answers

On file /application/config/database.php where is

$db['default']['hostname'] = 'localhost';

must be

$db['default']['hostname'] = 'mysql:host=localhost';

localhost or your database host.

like image 72
MrGusMuller Avatar answered Oct 24 '22 09:10

MrGusMuller


This should not be the case.

localhost;dbname=testdatabase

should be

mysql:dbname=testdatabase;host=localhost;
like image 34
Mike Mackintosh Avatar answered Oct 24 '22 08:10

Mike Mackintosh


PDO driver require a full DSN string to be provided. The string like this

'dsn' = ‘mysql:host=localhost;dbname=databasename’;

when you use this string you should remove host and databasename value from array. I think following example gives you an idea.

$db['default'] = array(
'dsn'   => 'mysql:host=localhost;dbname=codeigniter3',
'hostname' => '',
'username' => 'root',
'password' => '',
'database' => '',
'dbdriver' => 'pdo',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

Thanks

like image 21
Yusuf Avatar answered Oct 24 '22 08:10

Yusuf