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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s