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.
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.
This should not be the case.
localhost;dbname=testdatabase
should be
mysql:dbname=testdatabase;host=localhost;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With