Connect MySQL using PHP

In order to store data in MySQL database, connection establishment is required. In PHP connecting to database is pretty simple to be done. You have to be familiar with a sing function mysql_connect() or mysqli_connect(). Well, mysqli is the extended version of mysql functions.


MYSQLI_CONNECT()

mysqli_connect consists of 4 arguments.
mysqli_connect($host_name, $username, $password, $database_name);


$host_name : Host name or an ip address. (“localhost” is most likely the host name if you are using a cpanel server).
$username : Privileged username of MySQL. “root” is the default username.
$password : Password of MySQL.  ” ” is the default password.
$database_name : Database you created in MySQL.

EXAMPLE PROGRAM:
<?php
//declare connection requirements
      $host_name = “localhost”;
      $username = “root”;
      $password = “”;
      $database_name = “database_2015”;

//connection establishing
//store the connection in a variable named $conn or anything.

      $conn = mysqli_connect($host_name, $username, $password, $database_name);

//check connection is successful or not

 if(mysqli_connect_errno()){
      die(“ERROR :”.mysqli_connect_error());
 }
 else{
      echo “Connection Successful”;
 }
?>

mysqli_connect_errno()

This function returns the error code from last connect call.


mysqli_connect_error()

This function returns a string description of the last connect error.


Advertisements