How to Closes a previously opened database connection (MySQLi) in PHP ?


To close a previously opened database connection in MySQLi, you can use the close() method of the MySQLi object. Here are the steps to do it:

  • Create a MySQLi object and connect to the database:
$mysqli = new mysqli("localhost", "username", "password", "database_name");
  • Use the close() method to close the database connection:
$mysqli->close();

Here's an example code that demonstrates how to close a MySQLi database connection:

// Create a MySQLi object and connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database_name");

// Check if the connection was successful
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    exit();
}

// Perform some database operations here...

// Close the database connection
$mysqli->close();

Alternatively, you can also use the mysqli_close() function to close the database connection. Here's an example:

// Create a MySQLi object and connect to the database
$mysqli = mysqli_connect("localhost", "username", "password", "database_name");

// Check if the connection was successful
if (!$mysqli) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}

// Perform some database operations here...

// Close the database connection
mysqli_close($mysqli);


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.