Home > Article > Backend Development > How to close database connection in PHP
PHP is a popular server-side scripting language that is widely used in web development. When interacting with the database, we need to open the database connection, but when the database connection is not needed, we need to close it. In this article, we will discuss how to close database connection in PHP.
PHP interacts with MySQL database
In PHP, we can use many different methods to interact with the MySQL database. Here is a simple example:
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功"; ?>
In this example, we use the mysqli object to create a connection to the MySQL server. If the connection fails, we print an error message. Once we successfully connect to the database, we can perform queries and other operations.
Close the database connection
After completing all required database operations, we need to close the database connection. PHP provides many methods to close MySQL connections. Here are some of the methods:
$conn->close(); // 使用 mysqli 对象的 close() 方法 mysql_close($conn); // 使用 mysql_close() 函数
In the above code, we use the close() function or mysql_close() function of the mysqli object to close the connection.
If you are using PDO, close the connection as follows:
$conn = null; // 使用变量 $conn 来关闭连接
In this example, we close the connection by setting the $conn variable to null.
These methods can successfully close the MySQL connection. We can use them when we are not doing anything, or we can use them when we need to reuse the connection resources in order to release the connection resources. Closing connections can help you avoid memory leaks and other problems.
Summary
In PHP, we can use mysqli objects or PDO objects to interact with the MySQL database. When dealing with database connections that are no longer needed, we need to explicitly close the database connection to release resources. We can use the close() function (mysqli) function, mysql_close() function or set the variable to null (PDO) to close the connection. These methods can successfully close MySQL connections to help you avoid memory leaks and other problems.
The above is the detailed content of How to close database connection in PHP. For more information, please follow other related articles on the PHP Chinese website!