PHP Tutorial 8: Connecting PHP script to MySQL

This tutorial will guide you to establish connection to the database. Means accessing data stored in database tables in MySQL.  Using this you can store user information into the tables and later display them on the web page. This will also guide you how to use a simple logic to display contents of database of the webpage using PHP

Before you can access the database from PHP script you need to establish connection to the MySQL. The function used to connect to the database is mysql_connect().

Following are the steps that will make PHP script connect to the database.

1.)    Use Connect Function: First of all we use mysql_connect() function and pass three parameters along with the function to check for the connection the three parameters are

  • Servername
  • Username
  • Password

Therefore the function is used as mysql_connect(servername,username,password)

2.)    Using the database: Next we use the database we have created to work on with. This is done using the function mysql_select_db().  This takes two parameters

  • Database name.
  • Variable we used to connect to the MySQL.

There for the final code for both the above steps looks as:

$connected= mysql_connect(localhost,root,12345);


As you can see in the second parameter in mysql_select_db() function used the variable used to store the connection. This is because the selection of database takes place if the connection is found.

3.)    Finally we close the MYSQL connection using mysql_close() function.

Example: Let me show you an example that connects to the database and displays the database on the webpage.

$hostname = "localhost";
$username = "root";
$password = "";
$database= "dba";

or die("Cannot connect to the database");
echo "Connected to the database";

$selected = mysql_select_db("dba",$connected)
  or die("Could not select database");

$result = mysql_query("SELECT * FROM authors order by sno");

while($row = mysql_fetch_array($result))
  echo "<font face ='lucida sans'>";
  echo "<br>".$row['sno'] . " " . $row['name'];
  echo "<br />";

The output of this script thus looks like this.

 The output on the webpage is same as that the contents in your database. The database table looks as:

If you have any doubts regarding the script do contact us in comments section. We will be glad to answer.