PHP Connection to a database

Written by admin on December 25th, 2007 in PHP Tutorials.

PHP and MySQL there has to be a connection somewhere to use them both. But how do you make a connection?

Below will show you.

First…

You should never store any of your connection information anywhere other than in a PHP
document.

Now lets get started.

Create a php file called config.php and place it in the same directory as your index page.

Open config.php and insert the following code:

<?php

$connection mysql_connect(“localhost”“db_username”“db_password”);

$db mysql_select_db(“db_name”$connection);

?> Lets run through that code.

Firstly we want to store our connection into a variable .

So we give it a variable name of connection.

This connection variable then holds the function of mysql_connect which connects to a db
using the host username and password that is provided.

To change the host, username, and password simply change the data in quotes.

A DB host is usually localhost unless you specify it in your Control panel for your databases.

Now we have another variable “db”. How would mysql_connect know what it was
reading from if it has no db?

So here we are using the function “mysql_select_db” which simply selects the db that we say.
Again you can change the db name in the quotes.

Once you’ve given all your info that’s it you should have a successful connection.

But what if you don’t?

Well you can either add this error handling to the mysql_connect function or use if statements.

To use the mysql_connect function for this you simply need to add the following die onto the
end of your mysql_connect function…

First loose the ;

or die(“Connection could not be made.”);

If a connection cannot be made the statement in quotes will be shown.

That’s how to connect to a DB with PHP.

Now all you have to do is include config.php into the file that needs a db connection.

Leave a Reply

You must be logged in to post a comment.



Site Navigation