Reputation: 167
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.
Upvotes: 5
Views: 3464
Reputation: 3997
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.
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>
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).
Upvotes: 5
Reputation: 2984
I believe this link will give you better understanding of how to use PDO;
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
If you include necessary files in your login.php and if you already established connection using PDO in one of the included necessary files (lets call it $db) you can make a simple check;
<?php
if ($db) {
//connection is established already
}else {
//connection is not established, try to connect to database last time, if you can't show error etc..
}
?>
I hope, I understood you correctly and this will be helpful for you.
Upvotes: 1