Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a PDO object be stored in session?

Tags:

php

session

pdo

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 ?
like image 263
Virus721 Avatar asked Sep 29 '12 10:09

Virus721


1 Answers

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.

like image 174
JvdBerg Avatar answered Sep 27 '22 20:09

JvdBerg