Last Update - 25 Oct 2017

How to create MySql database connection in php

How to create MySql database connection in php

How to connect to MySQL using PHP:

Whenever you want to save some important data on database you must need a connection between your project to MySQL. The tutorial takes you through establishing a connection using php  to MySQL in your project. Let's start, The function to connect to MySQL is called mysqli_connect. This function returns a resource which is a poin to the database connection.




Before you create a connection between php and MySQL you need some information regarding database server and store in your configuration file. for example:

$servername = "servername";
$username = "username";
$password = "password";
$database= "database";


After collect these information you need to create a config.php file, this file you can use in your all file of your project where you want database connection.

Finally create config file:



$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";

// Create connection
$connection = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$connection) {
    die("Connection failed: " . $connection->connect_error);

function close_db(){



Did you find this page helpful? X