After you have verified that your server supports PHP (see older post PHP/MySQL Tutorial Part 1), you can go ahead to create a database, and connect to it. Usually Linux server packages comes with tools like cPanel, where you can create a database, a user and a password on a web interface. It is relatively simple, and hence we are not going to discuss it here.
To connect to a database, you would need to know:
1. Host address – 95% is ‘localhost’ but sometimes it can be different. Eg. for iPowerWeb, it should be ‘username.ipowermysql.com’.
2. Database name
3. A username
4. A password
It is easier to start with a code snippet:
<?php
$dbhost = ‘localhost’;
$dbname = ‘databasename’;
$dbuser = ‘username’;
$dbpass = ‘password’;
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (‘Error connecting to database’);
mysql_select_db($dbname);
?>
The first part of the code specifies the host address, username and password of the database. The second part basically connects to the database. If it failed, it would output ‘Error connecting to database’.
The last line of the code simply selects the database to connect to.
It is also a good idea to close the connection after any operation is done. Use this code:
<?php
mysql_close($conn);
?>
Usually we would put the first code in a file named ‘connect.php’ or ‘config.php’, and include it at the beginning of the file. At the end of the file, we would include the last code which is saved in a file named ‘close.php’.