mysqli close() Method
The mysqli::close() / mysqli_close() function is used to close a previously opened database connection.
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it is a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.
Syntax
//Object-oriented style public mysqli::close() //Procedural style mysqli_close(mysql)
Parameters
No parameter is required.
Return Value
Returns true on success or false on failure.
Example: Object-oriented style
The example below shows the usage of mysqli::close() method.
<?php //establishing connection to the database $mysqli = new mysqli("localhost", "user", "password", "database"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: ". $mysqli->connect_error; exit(); } //getting query result from the database $sql = "SELECT Name, Age FROM Employee ORDER BY Age"; $result = $mysqli->query($sql); //closing the connection $mysqli->close(); //processing the data retrieved from the database //- fetching all result rows as associative array $rows = $result->fetch_all(MYSQLI_ASSOC); //displaying the rows foreach ($rows as $row) { printf("%s, %d\n", $row["Name"], $row["Age"]); } ?>
The output of the above code will be:
Marry, 23 Kim, 26 John, 27 Adam, 28
Example: Procedural style
The example below shows the usage of mysqli_close() function.
//establishing connection to the database $mysqli = mysqli_connect("localhost", "user", "password", "database"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: ". mysqli_connect_error(); exit(); } //getting query result from the database $sql = "SELECT Name, Age FROM Employee ORDER BY Age"; $result = mysqli_query($mysqli, $sql); //closing the connection mysqli_close($mysqli); //processing the data retrieved from the database //- fetching all result rows as associative array $rows = mysqli_fetch_all($result, MYSQLI_ASSOC); //displaying the rows foreach ($rows as $row) { printf("%s, %d\n", $row["Name"], $row["Age"]); } ?>
The output of the above code will be:
Marry, 23 Kim, 26 John, 27 Adam, 28
❮ MySQLi Functions Reference