Virus721
Virus721

Reputation: 8335

Can a PDO object be stored in session?

I have two questions:

and then store this $statement in $_SESSION and reuse this statement, or should I do the same thing (PDO::prepare) again next time I want to perform this same query (with different values for the bindings)?

Upvotes: 10

Views: 4096

Answers (2)

undefined
undefined

Reputation: 2101

Actually 'You cannot serialize or unserialize PDOStatement instances' (quoting the actual exception message). Here the full message:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDOStatement instances' in [no active file]:0
Stack trace:
#0 [internal function]: PDOStatement->__sleep()
#1 {main}
  thrown in [no active file] on line 0

As for why - it's already answered here.

Upvotes: 2

JvdBerg
JvdBerg

Reputation: 21856

You should not store PDO objects in sessions.

Best (and only right) way to use PDO objects is to create them on every request to the server.

The benefit from prepared queries is 2 way:

  1. When doing the same query multiple times there is a speed advantage
  2. There is the possibility of parameter binding, to prevent SQL injection.

When storing a PDO resource in a session, there will be a build up of open connections to the database as requests from different clients come in. PDO does connection pooling, trying to keep connections to the database to a minimum, but still having some connections open for speed. By storing pdo connections in a session, that mechanism is killed. And the performance will suffer.

Upvotes: 9

Related Questions