PHP close() and mysqli_close() | Close Database Connection

This article is created to cover the two functions of PHP, that are:

Both the functions are used to close a previously opened connection to the database. The only difference is, the close() works with PHP MySQLi object-oriented script, whereas the mysqli_close() works with PHP MySQLi procedural script.

PHP close()

The PHP close() function is used to close a previously opened database connection in PHP MySQLi object-oriented style. For example:

<?php
   $server = "localhost";
   $user = "root";
   $pass = "";
   $db = "fresherearth";
   
   $conn = new mysqli($server, $user, $pass, $db);
   
   if($conn -> connect_errno)
   {
      echo "Connection to the database failed!<BR>";
      echo "Reason: ", $conn -> connect_error;
      exit();
   }
   else
   {
      echo "Connection to the database, established.";
      
      // block of code, to process further...
   }
   
   $conn -> close();
?>

Note: The mysqli() is used to open a connection to the MySQL database server, in object-oriented style.

Note: The new keyword is used to create a new object.

Note: The connect_errno is used to get/return the error code (if any) from last connect call, in object-oriented style.

Note: The connect_error is used to get the error description (if any) from last connection, in object-oriented style.

Note: The exit() is used to terminate the execution of the current PHP script.

PHP close() Syntax

The syntax of close() function in PHP, is:

connectionVariable -> close();

PHP mysqli_close()

The PHP mysqli_close() function is used to close a previously opened database connection in PHP MySQLi procedural style. For example:

<?php
   $server = "localhost";
   $user = "root";
   $pass = "";
   $db = "fresherearth";
   
   $conn = mysqli_connect($server, $user, $pass, $db);
   
   if(mysqli_connect_errno())
   {
      echo "Connection to the database failed!<BR>";
      echo "Reason: ", mysqli_connect_error();
      exit();
   }
   else
   {
      echo "Connection to the database, established.";
      
      // block of code, to process further...
   }
   
   mysqli_close($conn);
?>

Note: The mysqli_connect() is used to open a connection to the MySQL database server, in procedural style.

Note: The mysqli_connect_errno() is used to get/return the error code (if any) from last connect call, in procedural style.

Note: The mysqli_connect_error() is used to return the error description (if any) from the last connection, in procedural style.

PHP mysqli_close() Syntax

The syntax of mysqli_close() function in PHP, is:

mysqli_close(connectionVariable);

PHP Online Test


« Previous Tutorial Next Tutorial »