How to Connect Database in PHP

How to Connect Database in PHP

Connect MySQL database using a PHP script. This tutorial shows you, how you can connect the MySQL database using PHP.

You will also learn the MySQL database connection function, For connecting your MySQL database using a PHP script.

Connect MySQL Database Using PHP Script

Before you create a database connection using a PHP script, you must know about the PHP MySQL connection function:


PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure.




The hostname that runs the database server If not specified, the default value will be localhost.


Username accessing the database If not specified, the default will be the name of the user who is the owner of the server process.


The default value is defined by MySQL default password. In SQL secure mode, this parameter is ignored and a blank password is used.


If mysql_connect () is called with other arguments, no new connection will be established. Instead, the identifier of the already open connection will be returned.


  • MYSQL_CLIENT_SSL – Use SSL encryption.
  • MYSQL_CLIENT_COMPRESS – Use Compression Protocol.
  • MYSQL_CLIENT_IGNORE_SPACE – Allow the location after the function names.
  • MYSQL_CLIENT_INTERACTIVE – Allow passive seconds of idle time before closing connection.
  • Example For MySQL Connection

PHP Script to Connect MySQL Database:

Now you can create a db.php file and update the below code in your file for connecting a MySQL database:

$host= "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($host, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
echo 'Connected successfully';



In this tutorial, you have learned how you can easily connect the database using PHP script.

Leave a Reply

Your email address will not be published. Required fields are marked *