Connecting To A Database

April 13th, 2009 | Tags: ,

Tutorial Description:

Learn how to use PHP to connect to a MySQL database.

OK, first of all, make sure your host supports a recent version of PHP & MySQL. It’s generally better to use a special connection file, separate from your coding file, so if someone succeeds to hack into the main file, he won’t get the database info.

To be able to connect to any database, the database needs to exist, so after you create a new database, you’ll need to attach a username to that database, and then connect via that username [and password].

So lets create a new file, called connect.php

<?php

// Define connection variables...
$c_username = "database_username";
$c_password = "password";
$c_host = "localhost";
$c_database = "database_name";

// Lets actually connect.
$connection = mysql_connect($c_host, $c_username, $c_password)
or die (
"It seems this site's database isn't responding.");

mysql_select_db($c_database)
or die (
"It seems this site's database isn't responding.");

?>

Of course you’ll need to edit the variables in the code snippet for it to work.

After that, all you need to do is include that file to be connected, like so:

<?php

// Include the connection file.
include("connect.php");

?>

Thats about it, after connection, you can query the database as you like.

No comments yet.
TOP