How to Connect MySQL database using PHP

How to Connect MySQL database using PHP


How to Connect MySQL database using PHP

Today I am going to show you how to connect MySQL database using PHP. Firstly you need xampp tool, it provides the Apache server and MySQL database. If you don't have please read and follow the instruction on how to install xampp on your windows 10.

How to connect MySQL database Using PHP


After installation the XAMPP follows the steps

  • Go to your XAMPP control panel
  • Active Apache and Mysql by clicking start Button
  • Go to C:/xampp/htdocs/

Create a folder within htdocs folder. In my case, I created a test folder. Then create a db.php file.

test/db.php

Declare the Database Connection Variables 

$HOST_NAME = "localhost"; 
$USER_NAME = "root"; 
$USER_PASSWORD = ""; 
$DATABASE_NAME = "accounts";
 
As you work in the local machine, so your HOST_NAME is localhost or you can use 127.0.0.1 IP address instead of type localhost.

Default USER_NAME is root if you didn't create another user. If you want to protect your database you can create a user and set a password and give this value to the $USER_NAME and $USER_PASSWORD variables.

Default $USER_PASSWORD is empty/null

Lastly, you need $DATABASE_NAME. So let's start to create a database, go to URL bar and type localhost/phpmyadmin or click this link localhost/phpmyadmin . After that Click new button , then give your DB name to the input field and create one.

Established Connection Using mysqli_connect() Method

$CONN = mysqli_connect($HOST_NAME,$USER_NAME,$USER_PASSWORD,
$DATABASE_NAME);
 
mysqli_connect() the function is used to connect the database. It has four arguments - HOSTNAME, USER NAME,USER PASSWORD,DATABASE NAME that already defined in the declaration block.

Check The Connection using $CONN Variable


 
if(!$CONN){
    echo "Connection failed ".mysqli_error();
    /* if you failed to established your connection then
       it returns this statements with MySQL error */
}else{
    echo 'Connected!';
}
 


If connection successfully established then $conn variables return true otherwise it returns false.
Place all codes in db.php file and run the file


Full code: 


<?php
// Declaration BLock
$HOST_NAME = "localhost";
$USER_NAME = "root";
$USER_PASSWORD = "";
$DATABASE_NAME = "accounts";

// Connect to the database make sure your Apache server is running
$CONN = mysqli_connect($HOST_NAME,$USER_NAME,$USER_PASSWORD, $DATABASE_NAME);
if(!$CONN){
    echo "Connection failed ".mysqli_error();
    /* if you failed to established your connection then
       it returns this statements with MySQL error */    }else{
    echo 'Connected!';
}
?>


Output

Connected!

Great! You did it. If you failed to connect your MySQL database using PHP feel free to comment and message us.


You may like these posts