MySQLi Procedural procedure:
To close the connection in mysql database we use php function mysqli_close() which disconnect from database. It require a parameter which is a connection returned by the mysql_connect function.
Syntax:
mysqli_close(conn);
If the parameter is not specified in mysqli_close() function, then the last opened database is closed. This function returns true if it closes the connection successfully otherwise it returns false.
Below program illustrate the mysqli_close() function
<?php $servername = "localhost"; $username = "username"; $password = "password"; Â Â // Creating connection $conn = mysqli_connect($servername, $username, $password); Â Â // Checking connection if (!$conn) { Â Â Â Â die("Connection failed: " . mysqli_connect_error()); } Â Â // Creating a database named newDB $sql = "CREATE DATABASE newDB"; if (mysqli_query($conn, $sql)) { Â Â Â Â echo "Database created successfully with the name newDB"; } else { Â Â Â Â echo "Error creating database: " . mysqli_error($conn); } Â Â // closing connection mysqli_close($conn); Â Â ?> |
MySQLi Object-oriented procedure::
To close the connection in mysql database we use php function conn->close() which disconnect from database.
Syntax:
conn->close();
Program: To illustrate the closing of connection in object-oriented procedure.
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; Â Â // checking connection $conn = new mysqli($servername, $username, $password, $dbname); Â Â // Check connection if ($conn->connect_error) { Â Â Â Â die("Connection failed: " . $conn->connect_error); } //Close the connection $conn->close(); ?> |
Using PDO procedure:
To close the connection in MySQL database in PDO procedure we set the connection name to null which disconnect from the database.
Syntax:
conn=null;
Program: to illustrate the closing of connection in PDO procedure.
<?php $servername = "localhost"; $username = "username"; $password = "password";   try {     $conn = new PDO("mysql:host=$servername;dbname=newDB",                      $username, $password);       // setting the PDO error mode to exception     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);       $sql = "CREATE DATABASE newDB";       // using exec() because no results are returned     $conn->exec($sql);       echo "Database created successfully with the name newDB";     } catch(PDOException $e)     {     echo $sql . " " . $e->getMessage();     } $conn = null; ?> |
References: http://php.net/manual/en/mysqli.close.php
