November 28, 2026
How To Close an Active MySQL Connection in PHP?
For closing an active MySQL connection there is mysqli_close() build in function present in PHP. If you does not close MySQL connection then at the end of your script all the active MySQL connections get close automatically. mysqli_close() function is usefull when you want to close a MySQL connection before end of script. The example is mentioned below:
Code
<?php
$connection = mysqli_connect("localhost", "marcus", "xyz123");
if (!$connection)
{
die("Could not connect: " . mysqli_connect_error());
}
mysqli_close($connection);
?>
FAQ
1. Is it necessary to close a MySQL connection in PHP?
No. PHP automatically closes active database connections when the script finishes executing. However, you can use mysqli_close() to close a connection earlier.
2. What does mysqli_close() return?
The mysqli_close() function returns true on success or false on failure.
3. How can I check whether a MySQL connection is closed in PHP?
You can use the mysqli_ping() function to check whether a connection is responsive before closing it. Once the connection is closed, you should not reuse it.