I am trying to write some code with multiple classes which will have a lot of DB connections/queries later.
My question is does PDO connect to database as soon as the following line is executed and it will stay connected until it is closed?
$pdo = new PDO($dsn, $user, $pass, $options);
Or it waits until we do the following to connect, for example:
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();
// Closing connection
$stmt = null;
If it isn't connected immediately when we do new PDO()
then I can easily make the $pdo
variable global and use it in every class, otherwise I have to connect in each class separately with __construct()
method and then close connection on __destruct()
method. (I'm still not sure if this is the best way to go for better performance)
P.S. Do we also need to set $pdo = null
to close the connection? or $stmt = null
is enough?