【问题标题】:Do I need to close the mysql connection of this code or is this ok? [duplicate]我需要关闭这段代码的mysql连接还是可以? [复制]
【发布时间】:2020-03-09 02:20:09
【问题描述】:
public function getActiveUsers(){
    $result = $this->con->query("SELECT * FROM `USERS` where `IsActive`=1");
    $users = array();
    while ($item = $result->fetch_assoc()) {
        $users[] = $item;
    }
    return $users;
}//End Function

这是我用来从我的数据库(我的仪表板)获取活跃用户的 PHP 函数。其他大部分函数都是这样写的。它们写在一个 PHP 文件 (db-function.php) 中。但首先我在一个名为 DB-Connet.php 的文件中定义了连接。

public function connect()
    {
        require_once 'source/config/config.php';
        $this->con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
        return $this->con;
    }

然后在 db-function.php 中的 DbConnet 类的构造中创建连接。

function __construct()
    {
        require_once 'DB-Connet.php';
        $db = new DbConnect();
        $this->con = $db->connect();
        
    }

但是当我尝试访问仪表板网址时,它会显示这样的消息,

用户 adimn_user 在第 16 行 ..../db-function.php 中已经有超过 'max_user_connections' 个活动连接。

我做错了什么? (我的英语不好。很抱歉。欢迎编辑。谢谢大家。)

P.S : 像这样在 db-connect.php 的 _destruct 函数中关闭连接可以吗?

function __destruct() {
        $this->con->close();
  }

【问题讨论】:

  • 嗨,我修好了。实际上,发生此错误是因为我包含的“坏库”发出了许多不必要的数据库请求。我的服务器只允许每个用户 50 次调用。提示 - 始终确保优化后端代码并仔细检查每个外部库是否存在错误编码。

标签: php mysql


【解决方案1】:

如果不需要,请始终关闭 mysql 连接。它可以节省内存并为下一个可能访问数据库的请求释放连接。

【讨论】:

猜你喜欢
  • 2017-07-10
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多