I have a site with a login form. When the login form page is loading I create a new PDO object to see if the connection is working. If it is successful in opening a connection the viewer will see a login form. If it’s not successful they will get a message saying the server is down.
They then fill in their details and click login. The login process is via AJAX so the page will not reload and JavaScript will send their details of to a PHP file on the server.
How can I make use of the connection I established earlier?
I was thinking about using persistent connection but I don’t really understand what it does so I have know idea if it will help me. I don’t want to have to create a new connection and check if it works as we did it earlier.
So will a persistent connection work? I read the php.net documentation for it with MySQL but I didn’t understand it and couldn’t find any documentation for its usage with PDO.
Persistent connections are handled by PHP itself. You do not need to handle it other than activating it.
If you read the following page: https://www.php.net/manual/en/pdo.connections.php, you will get information about how to activate the persistent connection.
You need to execute this line everytime you want to "connect" to the database. If the connection already exists, it will use it under the hood.
And now, if you want to check if the connection worked, you have to use a try/catch (as explained in the link above).