Reputation: 8335
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)?
Upvotes: 10
Views: 4096
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
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:
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