PHP is used with MySQL to retrieve and store data from the database. When the script execution ends, the connection to the database needs to be closed. In this article, we will explain how to close a MySQL database connection in PHP.
Close the MySQL database connection
In PHP, to close the connection to the MySQL database, you must use the "mysql_close()" function. This function accepts a parameter representing the database connection.
For example:
mysql_close($connection);
In this case, $connection is the name of the connection variable.
Below is a complete example showing how to connect to a MySQL database, and how to close the connection.
<?php // 定义 MySQL 数据库连接变量 $dbhost = 'localhost'; $dbuser = 'username'; $dbpass = 'password'; $connection = mysql_connect($dbhost, $dbuser, $dbpass); // 如果无法连接到数据库,则显示错误信息 if(! $connection ) { die('无法连接: ' . mysql_error()); } echo '连接成功'; // 关闭数据库连接 mysql_close($connection); ?>
In the above example, if it cannot connect to the MySQL database, PHP will exit with an error message. If the connection is successful, the message "Connection successful" will be displayed. At the end of the script, close the database connection using the "mysql_close()" function.
Summary
This article explains how to close a connection to a MySQL database in PHP. After using the database, be sure to remember to close the connection to release resources. Otherwise, the connection will consume server resources and may cause performance issues.
The above is the detailed content of How to close MySQL database connection in PHP. For more information, please follow other related articles on the PHP Chinese website!