Last Update - 02 Jul 2020

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 the database you just 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 point to the database connection.

mysqli_connect();

Top 50 MySQL Interview Questions and Answers

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:

<?php
$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(){
	mysqli_close($connection);
}
?>

More For You

Did you find this page helpful? X