lang="en-US"> PHP Tutorial: Connecting to a MySQL Database –, LLC

PHP Tutorial: Connecting to a MySQL Database

You would think this is really obvious but I see a TON of posts on (great php/mysql forum by the way) where people put their login and password for their database on every page from a non-protected directory. Yikes!! This is a big no-no!

So, here’s the low down on how to setup a connection to a MySQL database using PHP and make sure your login information is protected. First, you’ll need a database, PHP, and a place to host your files. Once you have those you’re ready to go. Don’t have a hosting provider? No problem, check out XAMPP.

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 accidentally 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.

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.php. You want this file to be publicly accessible to anyone. Put this inside of it:

If you don’t get an error message when you try to view this php script then you know your include was successful. 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 huh?

You may also like...

1 Response

  1. I’m amazed, I have to admit. Rarely do I come across a blog that’s both equally
    educative and entertaining, and let me tell you, you have hit the nail on
    the head. The issue is something too few folks are
    speaking intelligently about. I’m very happy I came across this during my hunt for something relating to this.

Leave a Reply