Page 1 of 1

My Database Snippet

Posted: Tue Oct 04, 2011 8:37 am
by MattSheppard
Hi everybody,
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.");	
		}
	}
Thanks in advance,
Matt

Change: My question was answered in one of the other forums, so I have made a change to this function

Re: My Database Snippet

Posted: Tue Oct 04, 2011 9:07 am
by VladSun
Some things to say at first glance:
1) don't use die(), throw an exception;
2) don't use function arguments to change the behavior of a function so much - better use two functions, which leads to using a class with 2 methods;
3) don't use internal variables to configure the data connection (i.e. $server), better pass this to the constructor (assuming you use a class as said in 2) )
4) in fact, it's not a Database class/function, it's MySQL_Database class/function :) What will happen to your function if you need PostGreSql e.g. :)

PS: Even by having only the name of your function, it must be implemented as a class :) - it's a noun and there is no verb in it.

Re: My Database Snippet

Posted: Tue Nov 01, 2011 8:30 am
by Eric!
I would also suggest you look into using PDO