I’ve got a ‘best practice’ question about using PDO. I’m trying to finally get into object-oriented development and away from the PHP habits I developed ten years ago.
My normal method of development was to open a DB connection at the beginning of a script/page, then do a bunch of mysql_query calls as needed (mostly SELECT and INSERT). I’m using PDO for the first time, and it looks like the practice here is to create distinct PDO objects for each query/transaction. These seems like it would create multiple connections to the same DB during a string, which seems like a lot of unnecessary overhead.
Is my read on this totally wrong?
My apologies if this is covered somewhere I missed. I did look through StackOverflow, php.net, and a PHP 5.3 book I have.
No, you should not create multiple instances of PDO in that case. Just create 1 instance and use
PDO::query()on it. For example:If the query contains parameters, then prefer using
PDO::prepare()andPDOStatement::execute()instead ofPDO::query(). You can find an example in the documentation forPDO::prepare().