How to use pdo in codeigniter?

2019-05-04 16:18发布

问题:

As I know PDO support has been added to codeigniter recently but I can't find any documentation or tutorial about how to actually use it. Can anyone tell how can I use it?

回答1:

You can edit /application/config/database.php and to enable the PDO driver:

$db['default']['hostname'] = 'pgsql:localhost'; 
// or mysql:localhost
// or sqlite::memory:
$db['default']['dbdriver'] = 'pdo';

If you want to directly get you hand on the active DB connection. This might work, but I am not CI developer .. so no guarantees. I tried to understand that brain rotting code, but i suspect, that i failed. I'm not good at PHP4 + eval():

$CI = get_instance();
var_dump($CI->db->conn_id);
// should show that conn_id is instance of PDO


回答2:

Well, since CodeIgniter is merely a PHP framework, nothing prevents you from using it natively, as in $pdo = new PDO(...);.

However, when they say PDO is now supported, I think they mean their normal Database class now uses PDO (rather than MySQLi or the such).