Database Connection in PHP

 This blog explains about Database Connection in PHP and is illustrated very well below :



       This post gives an information about how to connect PHP page to MariaDB. First open your admin page by using this url -> http://localhost/phpmyadmin/ now you can see the admin page.

How to connect to MySQL using PHP

This article describes several methods for connecting to a MySQL database using PHP:

  • MySQL Improved (mysqli) extension
  • PDO (PHP Data Objects)
  • Legacy MySQL (mysql_) functions
  • Connecting to a remote MySQL database using PHP
The MySQL databases and users must already exist before you can use these methods. For information about how to manage MySQL databases using cPanel

In that page, you can see the user account in menu. Now select user account, here you can see the username and password of host which you have used as a server.


The MySQL Improved extension uses the mysqli class, which replaces the set of legacy MySQL functions.

To connect to MySQL using the MySQL Improved extension, follow these steps:

  1. Use the following PHP code to connect to MySQL and select a database. Replace username with your username, password with your password, and dbname with the database name:
        $mysqli = new mysqli("localhost", "username", "password", "dbname");
  2. After the code connects to MySQL and selects the database, you can run SQL queries and perform other operations. For example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:

Here you can create your own username and password also or you can choose given username and password for connecting PHP with Database.

The following program shows how to establish connection between PHP page with Database.

I am using the given username and password for your convenience. Ok, Lets go to the program.

/* Connect to Database */

$host = “localhost”;    // This is host name
$user = “root”;            // This is username
$pass = “”;                   // This is password( No password is given)
$connect=mysql_connect($host, $user, $pass); // gives connection between php and databse
echo “Successfully connected to database”;        // for our confirmation


Successfully connected to database