What are the potential pitfalls of storing PDO instances in session variables in PHP?

Storing PDO instances in session variables can lead to potential issues such as resource exhaustion, as each PDO instance consumes memory and database connections. It is recommended to store only the necessary data in session variables and recreate the PDO instance when needed instead.

// Create a function to establish a PDO connection
function getPDO() {
    $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    return $pdo;
}

// Store only the necessary data in session variables
$_SESSION['user_id'] = 123;

// Retrieve the PDO instance when needed
$pdo = getPDO();
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $_SESSION['user_id']]);
$user = $stmt->fetch();