Connect to MySQL Function

This is how I connect to a MySQL database. The following code is based off of three or four separate php files but could insecurely be combined into one. We’ll be creating functions.php which holds all of the code that the site uses, settings.php which holds the configurable options and a connection.php that connects to the database. The fourth and obviously optional file is your index.php (or wherever you’re connecting from)

First, in functions.php we’ll define our connectSQL. It takes four arguments and connects or returns an error if unsuccessful

?View Code LANGUAGE
1
2
3
4
5
6
7
8
9
10
11
function connectSQL($server, $user, $pass, $name) {
	define("DB_SERVER", $server);define("DB_USER", $user);define("DB_PASS", $pass);define("DB_NAME", $name);
	$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
	if (!$connection) {
		die("Database connection failed: " . mysql_error());
	}
	$db_select = mysql_select_db(DB_NAME,$connection);
	if (!$db_select) {
		die("Database selection failed: " . mysql_error());
	}
}

In settings.php we’ll assign values to the variables. Always remember to use secure passwords.

?View Code LANGUAGE
1
2
3
4
5
// Database Configuration
$database['server'] = "localhost";
$database['user'] = "xxx";
$database['password'] = "xxx";
$database['name'] = "xxx";

The actual connection code is now pretty easy to implement. You can call it whenever and however you’d like with only one line of code.

?View Code LANGUAGE
1
2
// Connection to the database via function
connectSQL($database['server'], $database['user'], $database['password'], $database['name']);

Finally, to actually use this, simply include the connection.php

?View Code LANGUAGE
1
include 'connection.php';

This entry was posted in Code and tagged , , , , . Bookmark the permalink.