To connecting MySQL Database, make sure you have MySQL running at a location to which your Web server can connect. Then you have created a user, password and the database to which you want to connect. The mysql_connect() is the first function in PHP to connect to MySQL.
The basic syntax for the connection is:
mysql_connect("hostname", "username", "password");
Using actual sample values, the connection function looks like this:
mysql_connect("localhost", "root", "pass");
This function returns a connection index (connection is succesful) or return false (connection fails). Lets see a working example of a connection script below. It assign the value of the connection index to a variable called $conn, then prints the value of $conn as proff of a connection. If you are not using password, just empty the password variable.
<?php $host="localhost"; $user="root"; $pass=""; $conn=mysql_connect($host, $user, $pass); echo "$conn"; //eof
Save this script as config.php (sometimes I save as config.inc), then place it on your work folder. Check the result on your web browser and you will see something like this:
Resource id #2
Connecting to MySQL using the mysql_connect() function is pretty straightforward. The connection closes when the script finishes its execution, but if you would like to explicitly close the connection, simply add the mysql_close() function at the end of the script.
And now we will try to connecting a Database, using function called mysql_select_db() with the following syntax:
mysql_select_db($db,$conn);
To connect to a database named test_conn, first use mysql_connect(), then use mysql_select_db(), like this:
<?php $host="localhost"; $user="root"; $pass=""; $db="test_conn"; $conn=mysql_connect($host, $user, $pass); mysql_select_db($db,$conn); //eof
You can modified simple connection script above by adding error message. The mysql_error() function will return a helpful error message when there is a mistake. Don’t forget to insert conjunction with the PHP die() function. See the modified script below:
<?php
$host="localhost";
$user="root";
$pass="";
$db="test_conn";
$conn=mysql_connect($host, $user, $pass);
if (!$conn){
die('Could not connect Database.'.mysql_error());
}
mysql_select_db($db,$conn);
//eof
Move on to the next section to start inserting data into your table, and soon you’ll be retrieving and formatting it via PHP. Good Luck.
