Establishing a Database Connection Using PHP

By Bangar CH

January 19, 2017

database, MySQL, PHP

In this tutorial, we'll show how to establish a database connection to your MySQL database using PHP.

PHP and MySQL is one of the most common stacks for web development. With it such a common combination powering so many websites.

Database Connection settings

To be able to connect to a MySQL database, you need to update the following MySQL Database Connection Credentials.

Before that make sure to create a Database name, Database username​ and Password for your database user. 

Database Name, Database USER and Database Password can be created from your cPanel or from shell.​

DATABASE NAME, DATABASE USER, PASSWORD, HOSTNAME

Now, you've to create a sample.php file and copy the below code and replace the fields with your DATABASE Credentials. The below is how it looks in your terminal and the code follows.

Database connection code in terminal

================================================
<?php

//ENTER YOUR DATABASE CONNECTION INFO BELOW:

$hostname="localhost";
$database="test_db";
$username="test_user";
$password="qwe234@#$";

//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Host SUCCESS! " .$hostname . "
" . PHP_EOL;
}

$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can't select database: ' . mysql_error());
}
else {
echo 'You have successfully established a connection to your DB ' . $database . '';
}

mysql_close($link);

?>
=============================================

Just RUN this sample.php files in your browser and you can see the below result on browser.

                                                                   http://IP/sample.php
Host SUCCESS! localhost You have successfully established a connection to your DB test_db
Conclusion

Finally, after complete reading this article you can surely connect your database using PHP.

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Create a website in 3 simple steps

Choose a website template, add features, then customise! - Free Online Website builder.