The mysqli_close()
function in PHP is used to close a previously opened MySQL connection. It's an important function to call after finishing database interactions to free up system resources. While it's not strictly necessary, as PHP automatically closes the connection when the script ends, it's a good practice to close it explicitly to improve resource management.
Syntax:
mysqli_close($connection);
- $connection: This is the MySQL connection resource that you want to close. It is usually returned by
mysqli_connect()
.
Example 1: Basic Usage
In this example, a MySQL connection is established using mysqli_connect()
, some queries are executed, and then the connection is closed using mysqli_close()
.
<?php
// Connect to MySQL server
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check if the connection was successful
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Perform a query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Fetch and display results
while ($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row['name'] . "<br>";
}
// Close the connection
mysqli_close($connection);
?>
Example 2: Closing the Connection After Multiple Queries
Here’s an example where multiple queries are executed before closing the connection.
<?php
// Connect to MySQL
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check the connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// First query
$query1 = "SELECT * FROM products";
$result1 = mysqli_query($connection, $query1);
// Fetch and display results for first query
while ($row = mysqli_fetch_assoc($result1)) {
echo "Product: " . $row['product_name'] . "<br>";
}
// Second query
$query2 = "SELECT * FROM orders";
$result2 = mysqli_query($connection, $query2);
// Fetch and display results for second query
while ($row = mysqli_fetch_assoc($result2)) {
echo "Order ID: " . $row['order_id'] . "<br>";
}
// Close the connection
mysqli_close($connection);
?>
Notes:
- After calling
mysqli_close()
, you cannot use the$connection
variable for any further database operations. - If you don't explicitly call
mysqli_close()
, the connection will automatically close when the script finishes executing, but explicitly closing the connection can help free up resources sooner.
This function helps manage MySQL resources effectively, especially when handling multiple database connections or long-running scripts.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.