Development Information

May 15, 2009

How to connect using the Database Class

Filed under: Tutorials — Tags: — judda @ 7:00 pm

I have received questions about how to connect to your database using the database class.  So here is a quick tutorial on how you can connect to the database using the database class.

Firstly we need to start at the top of the PHP page with the following:

require_once ( “/path/to/database/class/database.php”);

For example, “/path/to/database/class” could be nothing meaning that it is in the same directory as the current file, or it could be something like this “include/”.

This will tell PHP that the information about the database class is found on the corresponding file.  After the database class is ‘require’d into the page, there are two ways that you can create the connection.

Method 1:

In the “database.php” file modify the lines that say:

$db_host = “hostname”; /* Normally ‘localhost’ */
$db_name = “database_name”;
$db_user = “database_user”;
$db_pass = “database_pass”;

To be the information for connecting to your database.

For example, if you connect to your database through “localhost” you would change “hostname” to “localhost” as well as for all of the other variables ($db_name, $db_user, $db_pass).

After the login information is all set up for the database class, all you will have to do in the original script is add the following:

$db = new Database (); //Change $db with any variable name you would like your database connection to have

Method 2:

This method is a bit easier and will allow you to use any updated versions of the database class without actually having to remember to change the login credentials in the database.php file.  All you have to do is the following:

$db = new Database ( array ( “host” => “hostname”, “name” => “database_name”, “user” => “database_user”, “pass” => “database_pass” ) );

Where you fill in each of the credentials as they correspond to the values.  For example, if you connect to your database through “localhost” you would change “host” to “localhost” as well as for all of the other values (name, user, pass).

After doing this you should be connected to the database and able to run your queries.

Next Tutorial on how to run queries.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

ERROR: si-captcha.php plugin says GD image support not detected in PHP!

Contact your web host and ask them why GD image support is not enabled for PHP.

ERROR: si-captcha.php plugin says imagepng function not detected in PHP!

Contact your web host and ask them why imagepng function is not enabled for PHP.

Powered by WordPress