Connecting to the database server, when and where?
Posted: Fri Mar 12, 2010 7:19 am
I thought about connecting to database servers and some aspects that revolve around it. My particular interest is when (and to a lesser degree where) should the connection to the server be made. When you are connecting to a database server, when is the best place to do this?
If you are writing a plug-in that requires database connectivity, it’s probably best not to assume anything and connect to the db server afresh. A better alternative could be to check if a connection has already been made and if it still exists. With this information you could then determine whether to make a connection or not. Is there a php function that can check for an existing connection, or should I create a function for this purpose? Something similar to :
Now to the where part. If I am using a class, what would be the best practise for connecting to a database.
Connect via the __construct()?
Am I correct in saying that whenever a new Pressume object is instantiated, that a connection to the database will be made?
Connecting in the method.
Connecting on the page. If my page is called ‘something.php’, I make the connection on the page itself, through a method in my Pressume class.
A final question, if you are writing the code and you don’t know the values of the login details (and adding these details is up to a 3rd party), what would be the best place to put them, inside an external file such as ‘details.php’ where each value is defined, or inside the class?
If you are writing a plug-in that requires database connectivity, it’s probably best not to assume anything and connect to the db server afresh. A better alternative could be to check if a connection has already been made and if it still exists. With this information you could then determine whether to make a connection or not. Is there a php function that can check for an existing connection, or should I create a function for this purpose? Something similar to :
Code: Select all
<?php
function checkServerConnection() {
$pingServer = @mysql_ping();
if (!$pingServer) {
//connect to the database
}
}?>
Connect via the __construct()?
Code: Select all
<?php
class Pressume {
function __construct() {
$pingServer = @mysql_ping();
if (!$pingServer) {
//connect to the database
}
}
}?>
Connecting in the method.
Code: Select all
<?php
class Pressume {
function checkForArbValue() {
$this->connectToDb();
//continue with rest of the function.
}
}?>Code: Select all
<?php
$something = new Pressume;
$something->connectToDb();
// etc.
?>