David Grenier
David Grenier

Reputation: 1241

Multiple PDO instances in a script?

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.

Upvotes: 2

Views: 2080

Answers (3)

rid
rid

Reputation: 63442

No, you should not create multiple instances of PDO in that case. Just create 1 instance and use PDO::query() on it. For example:

$pdo = new PDO(...);

/* ... */

$pdo->query("SELECT * FROM table1");

/* ... */

$pdo->query("SELECT * FROM table2");

/* ... etc ... */

If the query contains parameters, then prefer using PDO::prepare() and PDOStatement::execute() instead of PDO::query(). You can find an example in the documentation for PDO::prepare().

Upvotes: 2

Madara's Ghost
Madara's Ghost

Reputation: 174957

The PDO Object stores the connection in which the queries are carried out. Normally, you only need one of those.

While there are cases where 2 connections might be convinient (When connecting to entirely different databases for instance), you generally only need one instance of the PDO class.

What you will have multiple instances of, is the PDOStatement class. Which stores the query statements themselves (as well as the results). So for every query you will have a single PDOStatement instance.

Upvotes: 2

ChrJantz
ChrJantz

Reputation: 929

yes, you initially connect to the database by creating an instance of the PDO object. But you use this object to run queries with and the results are packed into another class.

So you mainly have several classes with your query results, but just one connection to the database which runs the queries.

Upvotes: 0

Related Questions