Connect SQL Function
Original posted by: Admin on 01-02-2007
The easiest way to connect to a mysql database is with the mysql_connect function. Simply send it the database address, username the password and you'll be instantly connected. However, doing this on every single page can be time consuming and a nightmare to update when you change your username or password as you'll have hundreds of statements to update. The easier way to connect to your database is via a simple function.
function connect($host = 'host, $username = 'username', $password = 'password', $database = 'database') {
$link = mysql_connect($host, $username, $password);
if(!$link)
return 'Could not connect: ' . mysql_error();
else
return true;
}
If you put this function into a global config page all you'll ever have to do is call the function when you want to connect to the database, you don't even need to send it a username or password because its already in there, so now if you want to update your username and password you will only have to make one change, and thats in the global config page.
//Connect to the database using the default host, username and password
connect();
//Connect to the database with a unique host, username and password
connect('localhost', 'unique_username', 'unique_password');
This function can be slightly modified to auto choose a database as well.
function connect($host = 'host', $username = 'username', $password = 'password', $database = 'database') {
$link = mysql_connect($host, $username, $password);
if(!$link)
return 'Could not connect: ' . mysql_error();
else {
mysql_select_db($database, $link);
return true;
}
}
| Login to make a comment |
2 Comments Found |
|
| Mick | 15:04:12 28-01-2007 |
I guess it isn't really any easier if you are just using one database, but if you have several databases that you want to connect to it can be handy. For example;
$conn1 = connect(); <- Will connect to the default database
$conn2 = connect('localhost', 'username1', 'password1', 'database1'); <- Will connect to a second database
However with your script you would need to use a different script for each database. But I guess what ever suites your style.
Also I fixed up the typo :-)
|
| Anonymous | 14:56:07 28-01-2007 |
Two things. 1: $host = 'host will not work, you forgot a ' in there ^_^ 2: I use a page I call conn.php (short for connect) I just include it on all my pages that use it. It contains the following
$db = mysql_select_db("database"); ?>
I don't see how yours is any easier than mine.
|