I have a standard function that I have saved, that I put into just about all of my projects. I like to reuse my code and this (to me, at least seems) a standard piece of code to manage the killing of and connection to the MySQL database, but I'm not sure if there is a better way to do it. What do you all think? This is an annotated version I shared with a colleague.
Code: Select all
function Database($action = null){ # This function handles database connection and killing
/*
Usage guide:
Before a query is fired:
Database();
After the query is fired:
Database("kill");
This will open the database connection, execute your script, then close the database connection.
*/
$server = "live"; # Variable can be "dev" or "live", change this to change your connection string
switch ($server){
case "live":
$db["host"] = "localhost"; # Edit this to your host name
$db["user"] = "root"; # Edit this to your MySQL username
$db["pass"] = ""; # Edit this to your MySQL password
$db["database"] = "db"; # Edit this to the name of your database
break;
case "dev": # This is configured to work with a standard installation of WAMP Server, the layout is as above
$db["host"] = "localhost";
$db["user"] = "root";
$db["pass"] = "";
$db["database"] = "db";
break;
}
$db["connection"] = mysql_connect($db["host"], $db["user"], $db["pass"]) or die ("Failed to connect to database server.");
mysql_select_db($db["database"], $db["connection"]) or die ("Failed to connect to the database");
if ( $action == "kill" ){
mysql_close($db["connection"]) or die ("Failed to close the connection to the database.");
}
}Matt
Change: My question was answered in one of the other forums, so I have made a change to this function