lang="en-US"> Connecting to a MySQL Database Using PHP –  Design1online.com, LLC

Connecting to a MySQL Database Using PHP

You would think this is really obvious but I see a TON of posts on devnetwork.net (great php/mysql site) where people include their database login/password in every page from a non-protected directory. Big no no!

So, here’s the low down on how to setup a connection to a mysql database using php and keep your login protected. First, you’ll need a database, php, and a place to host both. Once you have those you’re ready to go.

1) You want your login for your database to be protected. That means you want the file to reside in a non-public part of your website. For instance, in most hosting places when you go to view all of your files you know to put them in the public_html folder or the www folder or the index folder. Your database login needs to be in the directory ABOVE your public folder. For most people this is called home, the name of your website, or even the root directory.

1) Create a file called dbconnect.php (or any other name that suits your fancy) in your home/root directory. That means if people navigate your website they’ll never be able to accidently access this information because your home/root directory has different chmod permissions (711) then your public_html directory (750).

2) Now you need to write the code to make the actual connection to the database in dbconnect.php.

<?php

//replace things with { } curly brackets with the appropriate information
//including the curly brackets! don’t leave those in there…
//connect to the server
mysql_connect(“localhost”, “{username}”, “{password}”)
or die (‘cannot connect to database because ‘ . mysql_error());

//select the database you’re going to use
mysql_select_db (“{databasename}”)
or die (‘cannot select this database because ‘ . mysql_error());

?>

3) That’s it for the code to connect! Short and sweet. Now the question is how to get it in all your files.

4) Create a file in your public_html folder called dbconnect_test.php. You want this file to be publically accessible to anyone. Put this inside of it:

<?php

//include your database connection from a protected directory
//by include it from the directory above (../) where this file is
include(‘../dbconnect.php’);

//do all the rest of your usual php coding here
echo “connection successful!”;

?>

If you don’t get an error message when you try to view this php script then you know your include was succesful. Now there’s no chance someone can get the login and password for your database and you can access it from your php files like you normally would AND you don’t have to rewrite the connection statement at the top of EVERY php page you make. Nifty.

You may also like...

Leave a Reply