Before you can use a MySQL database in your scripts, you must let your script know which MySQL database you plan to use and how to connect to it.
You will need to know the host computer where the database lives – usually localhost – and the username and password that will allow you to connect to the database.
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
Of course, you will need to replace your username and password as well as your host name if it’s located on a server other than the server where your scripts are located.
Once you have these variables setup you can connect to the database:
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die;
Once you’ve connected to MySQL, you’ll need to tell MySQL which database you want to use:
$dbname = 'cpuser_test';
If you are using my cpanel hosting, your database name will be the cpanel username_dbname. In the example above, my cpanel username is cpuser and the database name is test. It may be different at your hosting company.
This script that connects to the database will be more secure if you keep it in a private area of your site such as a level up from your public_html (or whatever your hosting provider names your root webspace). Your hosting company may not give you a private area (GoDaddy doesn’t give you a private area unless they’ve changed recently). If my host didn’t give me a private area, I would changes hosts. You don’t want anyone to access your database login information. Anything in your public area *could* be accessed much easier than in your private area, so it’s a good idea to have the script in the private area and just include it in the public scripts like this:
You can close the database connection like this:
Closing the connection is not always necessary since non-persistent MySQL connections are automatically closed when a script finishes executing.