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:

Plain Text   view plain   expand/collapse
  1. <span style="color: #000000"> <span style="color: #0000bb">&lt;?php
  2. $connection </span><span style="color: #007700">= </span><span style="color: #0000bb">mysql_connect</span><span style="color: #007700">(</span><span style="color: #dd0000">"localhost"</span><span style="color: #007700">, </span><span style="color: #dd0000">"db_username"</span><span style="color: #007700">, </span><span style="color: #dd0000">"db_password"</span><span style="color: #007700">);
  3. </span><span style="color: #0000bb">$db </span><span style="color: #007700">= </span><span style="color: #0000bb">mysql_select_db</span><span style="color: #007700">(</span><span style="color: #dd0000">"db_name"</span><span style="color: #007700">, </span><span style="color: #0000bb">$connection</span><span style="color: #007700">);
  4. </span><span style="color: #0000bb">?&gt;</span> </span>

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 ;

Plain Text   view plain   expand/collapse
  1. <span style="color: #000000"><span style="color: #007700">or die(</span><span style="color: #dd0000">"Connection could not be made."</span><span style="color: #007700">); </span></span>

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 SEO Services