In this tutorial we are going to discuss about, How to connect with database using php ? This tutorial is designed for beginners with little PHP experience.

At first we have to create four variables and store the database details inside these variables .

Host name is the name of your server .

$hostname = "localhost"; 

Username is the database username.The username is root by default in case of local server like xampp, wamp etc.

$username = "root";

Password is your database password.The password is nothing or blank by default.

$password = "";

and lastly we have the database named Test , here you can use your database name.

$database = "Test";

After that we create the connection with the above details .

Creating a new connection object using mysqli :

$connect = new mysqli($hostname, $username, $password, $database);

Now we Check the connection

if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
}else{
    echo "Connection successful";
}

If your connection is failed then it will stop execution and show you the error message “Coonection failed: ” and connection error problem, otherwise it will show you the message “Connection Successful”.

connect.php

<?php 
	
//These are the server and database details.
//The username is root by default in case of local server like xampp, wamp etc.
//password is nothing by default and lastly we have the database named Test. 

$hostname = "localhost";
$username = "root";
$password = "";
$database = "Test";
 
//creating a new connection object using mysqli 
$connect = new mysqli($hostname, $username, $password, $database);
 
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error 

if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
}else{
    echo "Connection successfully";
}

?>

Now you can execute it into your browser .

%d bloggers like this: