Create a Connection to MySQL Database In PHP



Database connection is very Important to access the data from the database(MySQL) in PHP. Through the database connection you can access the data from the database dynamically according to your requirement. In PHP it is very easy to create the Connection through the database This article will show you how to get up and running.

In PHP this can be done with the mysql_connect() function, it returns a resource which is a pointer to the database connection.

Step 1. Connect to the database / Open the database connection

mysql_connect(servername,username,password);

Use the below code for maintaning the connection in PHP

<?php
$servername = "your_server_name";
$username = "your_user_name";
$password = "your_password";

//connection to the database
$dbconnect = mysql_connect($servername, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>

Step 2. Select the Database
Once you will be connected, just select the database to work with let us assume that database name is EWA

<?php
//select a database
$database = mysql_select_db("EWA",$dbconnect)
or die("Could not select EWA");
?>

Step 3. Close the connection
Finally, we have to close the connection, it is optional because PHP closes the connection automatically when the scripts ends.

<?php
//close the connection
mysql_close($dbconnect);
?>

Now the connection file will look like as

<?php
$servername = "your_server_name";
$username = "your_user_name";
$password = "your_password";

//connection to the database
$dbconnect = mysql_connect($servername, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a database
$database = mysql_select_db("EWA",$dbconnect)
or die("Could not select EWA");

//close the connection
mysql_close($dbconnect);
?>

Now you have done, and include the connection on the page where you want to access it.