10

I have two questions:

  • To benefit from PDO prepared statements, should I first prepare a statement using a PDO object:

    $statement = $pdo->prepare($query, $bindings);

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)?

  • Is it useful to store the PDO object in $_SESSION when using PDO::ATTR_PERSISTENT when creating the PDO object ?
halfer
  • 19,824
  • 17
  • 99
  • 186
Virus721
  • 8,061
  • 12
  • 67
  • 123

2 Answers2

9

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.

JvdBerg
  • 21,777
  • 8
  • 38
  • 55
  • JvdBerg, you should explain why this is bad practice too! I'm curious as well. – danp Sep 29 '12 at 11:02
  • Thanks. You say : "When doing the same query multiple times there is a speed advantage". Is that true during a single HTTP request or over multiple ones ? – Virus721 Sep 29 '12 at 11:12
  • thats only true within the same http request. Think of updating multiple user accounts, with different data for example. The data goes in the binding, the query is prepared once. – JvdBerg Sep 29 '12 at 11:15
  • 4
    +1. In general, classes that contain _resources_ should not be stored in sessions, since they're not _serialisable_. More on that [here](http://php.net/manual/en/intro.session.php). – halfer Sep 29 '12 at 11:19
  • @halfer: PDO isn't a resource. It's an object, it **contains** a resource though. – Madara's Ghost Sep 29 '12 at 11:47
2

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.

Community
  • 1
  • 1
undefined
  • 2,051
  • 3
  • 26
  • 47