Connecting to a mysql database is pretty easy using php as it gives you all the commands you need in order to do it. This example is a basic way to do, there are other methods but I found this way useful when I was just starting out!

Here is an example of connecting and quering a mysql database


I usually store my connection attributes in another file and use a php include to call them. For added security I store my database connection details outside the web root.

The Include File

Create a new php file and call it something obscure as this, I always do this from habit, I never call my include file DatabaseConnect.php for example, if someone was browsing it would give the game away!

For now create the file MyCat.php and save it outside of your document root, for example in windows you could store it in c: and on a linux system in /home/me/ for example.

The MyCat.php file


Now when connecting and querying a database you would include the above file


This is now easier to manage as well, if you have multiple scripts that connect to a database then there is no need to keep adding your database connection information to the start of each script, you just have the one line to include it!