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

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

Both functions are used to close a previously opened connection to the database. The only difference is that close() works with PHP mysqli object-oriented script, whereas 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 = "codescracker";
   
   $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() function 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 or return the error code (if any) from the last connect call in object-oriented style.

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

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

PHP close() Syntax

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

connectionVariable -> close();

PHP mysqli_close()

In PHP mysqli procedural style, the mysqli_close() function is used to close a database connection that was already open. For example:

<?php
   $server = "localhost";
   $user = "root";
   $pass = "";
   $db = "codescracker";
   
   $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() function is used to open a connection to the MySQL database server in procedural style.

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

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

PHP mysqli_close() Syntax

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

mysqli_close(connectionVariable);

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!