我什么时候必须关闭 mysqli(数据库)连接? [英] When do I have to close mysqli (Database) connection?

查看:68
本文介绍了我什么时候必须关闭 mysqli(数据库)连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个 connect.php 文件,例如:

for now i have one connect.php file e.g.:

$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';"

in every other php file that uses MySQL queries, i use "include 'connect.php';"

对于 W3Schools 上的实例,他们为每个查询创建一个新连接,然后在使用后关闭它.请看这里:w3schools.com:我不确定他们这样做是否只是为了展示目的,或者这样做是否是最佳实践.

For Instance on W3Schools, they create for every query a new connection and then close it after use. see here: w3schools.com: Im not sure if they do it just for showing purpose, or if it is best practice to do it this way.

问题是,什么是最佳实践?我是否必须在每次选择后关闭连接,然后为下一个查询建立一个新连接?如果没有,我什么时候必须关闭连接?在所有查询的 php 文件的末尾?

The Question is, what is best practice? Do i have to close the connection after each selection and then establish a new one, for the next query? If not, when do I finally have to close the connection? On the end of the php File with all the queries?

谢谢

推荐答案

引用自 php.net 站点.

A quote from the php.net site.

打开的连接(和类似的资源)在脚本执行结束时会自动销毁.但是,您仍然应该在不再需要时关闭或释放所有连接、结果集和语句句柄.这将有助于返回更快地将资源转移到 PHP 和 MySQL."

"Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."

来源:http://php.net/manual/en/mysqli.close.php

你问什么时候,对不起,你看错了.希望这仍然有用.

You asked when, sorry overread that. Hope this will still be of any use.

这篇关于我什么时候必须关闭 mysqli(数据库)连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆