How can I use PDO in CodeIgniter 2?
I would like to use PDO instead of the built-in database-classes. But how can I do it? I tried to do the modifications suggested in a blog post. I commented out a part of system\database\DB.php
and also added:
$DB = new PDO(
$params['dbdriver'].':host='.$params['hostname'].';dbname='.$params['database'],
$params['username'], $params['password']);
return $DB;
But now my PHP-code crashes if I do $this->load->database();
in a Controller. So how should I use PDO and execute database queries using PDO in CodeIgniter?
I have also tried to use this code in a Controller:
foreach($this->db->query('SELECT * FROM users') as $row) {
开发者_高级运维print_r($row);
}
but it didn't work.
$stmt = $this->db->prepare("SELECT * FROM users");
$stmt->execute();
foreach ($stmt->fetch(PDO::FETCH_ASSOC) as $row) {
print_r($row);
}
Or:
foreach ($this->db->query("SELECT * FROM users") as $row) {
print_r($row)."\n";
}
Learn more about 3 PDO database calls here...
PDO Query
PDO Exec
PDO Prepare
EDIT: Also check your app/config/database.php
file for the following settings:
$active_group = 'default';
$active_record = FALSE;
$db['default']['hostname'] = 'YOURHOSTNAME';
$db['default']['username'] = 'YOURUSERNAME';
$db['default']['password'] = 'YOURPASSWORD';
$db['default']['database'] = 'YOURDATABASE';
$db['default']['dbdriver'] = 'mysql';
$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;
精彩评论