我什么时候必须关闭 mysqli(数据库)连接?
When do I have to close mysqli (Database) connection?
目前,我有一个 connect.php 文件,例如
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = new mysqli(
$mysql_host,
$mysql_user,
$mysql_password,
$mysql_database
);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
在使用 MySQL 查询的所有其他 PHP 文件中,我使用“include 'connect.php';”
对于 W3Schools 上的实例,他们为每个查询创建一个新连接,然后在使用后关闭它。请参阅此处:w3schools.com:我不确定他们这样做是否只是为了展示目的,或者这样做是否是最佳做法。
我是否必须在每次选择后关闭连接,然后建立一个新连接以用于下一次查询?如果没有,我什么时候最终必须关闭连接?在包含所有查询的 PHP 文件的末尾?
引自 php.net 网站。
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.
为该页面使用完连接后关闭连接。如果你有一个博客,你使用 post 的按钮将启动打开连接的代码,对连接做一些工作(比如将它添加到你的数据库或在页)然后它会关闭连接,这样它就不会打开超过它需要的时间。但是,当您再次单击该按钮时,它会重新开始该过程,仅在需要时使用资源。
最佳做法是在 footer.php
中使用关闭函数
目前,我有一个 connect.php 文件,例如
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = new mysqli(
$mysql_host,
$mysql_user,
$mysql_password,
$mysql_database
);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
在使用 MySQL 查询的所有其他 PHP 文件中,我使用“include 'connect.php';”
对于 W3Schools 上的实例,他们为每个查询创建一个新连接,然后在使用后关闭它。请参阅此处:w3schools.com:我不确定他们这样做是否只是为了展示目的,或者这样做是否是最佳做法。
我是否必须在每次选择后关闭连接,然后建立一个新连接以用于下一次查询?如果没有,我什么时候最终必须关闭连接?在包含所有查询的 PHP 文件的末尾?
引自 php.net 网站。
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.
为该页面使用完连接后关闭连接。如果你有一个博客,你使用 post 的按钮将启动打开连接的代码,对连接做一些工作(比如将它添加到你的数据库或在页)然后它会关闭连接,这样它就不会打开超过它需要的时间。但是,当您再次单击该按钮时,它会重新开始该过程,仅在需要时使用资源。
最佳做法是在 footer.php
中使用关闭函数