Home > Backend Development > PHP Problem > How to close MySQL database connection in PHP

How to close MySQL database connection in PHP

PHPz
Release: 2023-04-06 12:34:02
Original
791 people have browsed it

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);
Copy after login

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 = &#39;localhost&#39;;
$dbuser = &#39;username&#39;;
$dbpass = &#39;password&#39;;
$connection = mysql_connect($dbhost, $dbuser, $dbpass);

// 如果无法连接到数据库,则显示错误信息
if(! $connection ) {
   die(&#39;无法连接: &#39; . mysql_error());
}

echo &#39;连接成功&#39;;

// 关闭数据库连接
mysql_close($connection);

?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template