skip to content rich footer

stevenclark.com.au

subscibe to the StevenClark.com.au rss feed

SQL ConnectToDatabase Function

Carrying on from my last post about connecting to an SQL database using PHP, here are the functions I use to open and close database connections (Note: » just extends the line, you’ll need to remove that for this to work correctly).

// to open the database
function connectToDatabase ()	{
$link = mysql_connect("localhost", "database_name", »
                                  "database_password");
    if ($link && mysql_select_db("database_name"));
        return ($link);
	    return (FALSE);
}

// to close the database
function db_close($connecter)  {
    mysql_close($connecter);
}

It’s a good idea to keep these database connection functions in one place and then reuse them as you need, rather than repeating them everywhere.

Maintainability of your code is important even on smaller websites, if you only need to change a password in one place you’ll find life a lot easier. This code is very close to that found in PHP docs for mysql_connect, by the way. The connectToDatabase function returns a link identifier on success or FALSE on failure.

Further information in the mysql_connect documentation should take you an extra step as well.

So, in your PHP code where you want to run your SQL query all you need to do is something like the following snippet:


// connect to the database
include("down/in_some/folder/db_function_file.php");
$link = connectToDatabase();
    if(!link) {
        print "<p>database connection error</p>";
        mysql_close($link);
	exit();
}

Now run your query and put the values into variables, then explicitly close the link, and you’re done. Hopefully this snippet of advice might be useful.

Articles are licenced under a Creative Commons Licence but copyright of images is retained by © Steven Clark 2007 - 2008

One Response to “SQL ConnectToDatabase Function”

  1. Prevent SQL Injection Attacks in PHP : StevenClark.com.au

    [...] « SQL ConnectToDatabase Function [...]

skip to top of page

Currently Reading

Andy Clarke's Transcending CSS: the fine art of web design has been sitting on my bookshelf for several months and I've finally made the time to read it from end to end. My favourite thing about this book from the outset is that it's a designer's book, rather than a technician's manual, for web designers. The artwork and direction in Transcending CSS is enhanced by the attention to detail in the feel and texture of the book itself, the size of it's pages and the feel of the cover in your hands. It's definately a book that affords the act of being read. Looking forward to it.