I have a php page that requires a few queries from a database. So I have started writing down a few functions and I noticed I need to make sure that the connection is alive and it closes connection as the data retrieval is done. But it doesn’t take a genius to figure this is not the smartest way to deal approach this problem:
function getConnection() {
//it connects
}
function killConection() {
//it closes connection
}
function getData() {
getConnection();
//it gets data
killConnection();
}
function getVeryImportantData() {
getConnection();
//it gets data
killConnection();
}
//... and so on ...
I surely don’t want to establish a new database connection for each request I need to make, so I am wondering if there is a way to organize my code that will keep the connection alive while I need it, that will reconnect in case it is closed for any reason and disconnect when all the required operations are done.
What I would do:
$this->databaseConnectionproperty, this way you may check at a later time is you already have a database connection.This is a bit more complicated than a simple script, but I think it is worth a try. It will help you in planning your application the right way, it will also help in structuring your application properly.
Also, using PDO is good idea.
Let me know if you need help with this type of approach.