How to connect to MySQL database in PHP

Database connection is the first step to make your website to be able to fetch data from database or put some data to the database. With PHP we can easily connect our MySQL database to PHP website. 

If you also have this question that how to connect MySQL database in PHP and you are a beginner then I suggest you to start learning from procedural method of database connection.

How to Connect to MySQL database in PHP

PHP has a simple and easy inbuilt function mysqli_connect(). Which is used to connect a PHP website to MySQL database.

This function can take 6 arguments but we need to pass only 4 arguments - 

  • Host Name
  • Database Username
  • Database Password
  • Database Name
If the connection is successful, it returns connection object otherwise it returns Boolean value false.

Example - 

<?php
    $host = "Host_name";
    $uname = "Username";
    $password = "Password";
    $dbname = "Database_Name";
    $con = mysqli_connect($host, $uname, $password, $dbname);
    if(!$con)
    {
        echo "Error: Unable to connect to database";        
    }
?>


After making successful connection, you can insert, update, delete for fetch data to the database

Post a Comment

0 Comments