Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Which PHP function is used to disconnect from MySQL database connection?
PHP provides the mysql_close() function to disconnect from a MySQL database connection. This function takes a single parameter, which is a connection resource returned by the mysql_connect() function.
Syntax
bool mysql_close ( resource $link_identifier );
Here, if a resource is not specified, then the last opened database connection is closed. This function returns true if it closes the connection successfully, otherwise it returns false.
Example
The following example shows how to connect to and disconnect from a MySQL database −
<?php
// Connect to MySQL database
$connection = mysql_connect("localhost", "username", "password");
if (!$connection) {
die('Connection failed: ' . mysql_error());
}
echo "Connected successfully to MySQL database";
// Select database
mysql_select_db("database_name", $connection);
// Perform database operations here
// Close the connection
if (mysql_close($connection)) {
echo "Connection closed successfully";
} else {
echo "Error closing connection";
}
?>
Important Note
Deprecated Functions: The mysql_close() function along with other mysql_* functions have been deprecated since PHP 5.5.0 and removed in PHP 7.0.0. It is recommended to use mysqli_close() for MySQLi extension or PDO for database connections in modern PHP applications.
Modern Alternative
Using MySQLi extension −
<?php
$connection = mysqli_connect("localhost", "username", "password", "database_name");
// Perform database operations
// Close connection
mysqli_close($connection);
?>
Conclusion
While mysql_close() was used to disconnect from MySQL databases, modern PHP applications should use mysqli_close() or PDO for database operations due to security and performance improvements.
