【问题标题】:Does PHP close SQL connections opened with PDO at the end of the script if I don't explicitly close it?如果我没有明确关闭它,PHP 是否会关闭在脚本末尾使用 PDO 打开的 SQL 连接?
【发布时间】:2013-03-12 18:41:13
【问题描述】:

我知道我可以关闭一个 PDO SQL 连接,将处理程序设置为NULL

但如果我不这样做,PHP 会在脚本末尾关闭连接吗?

例如,我可以使用

$db = new PDO('sqlite:db.sqlite');
/* Code */
if ($cond1) { exit; }
/* More code */
if ($cond2) { exit; }
/* ... */
$db = NULL;
/* Code not related to the database */

...或者我应该使用这个:

$db = new PDO('sqlite:db.sqlite');
/* Code */
if ($cond1) {
    $db = NULL;
    exit;
}
/* More code */
if ($cond2) {
    $db = NULL;
    exit;
}
/* ... */
$db = NULL;
/* Code not related to the database */

【问题讨论】:

  • 是的,运行 1000 次并观察内存使用情况进行验证。
  • 是的,但最好明确关闭它

标签: php sql pdo connection database-connection


【解决方案1】:

根据docs

连接在该 PDO 对象的生命周期内保持活动状态。到 关闭连接,您需要通过确保 所有剩余的对它的引用都被删除——你通过分配来做到这一点 保存对象的变量为 NULL。如果你不这样做 明确地,PHP 将自动关闭连接,当您 脚本结束

【讨论】:

    【解决方案2】:

    示例。

    这是你的 dbc 类

    <?php
    
    class dbc {
    
        public $dbserver = 'server';
        public $dbusername = 'user';
        public $dbpassword = 'pass';
        public $dbname = 'db';
    
        function openDb() {    
            try {
                $db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
            } catch (PDOException $e) {
                die("error, please try again");
            }        
            return $db;
        }
    
        function getAllData($qty) {
            //prepared query to prevent SQL injections
            $query = "select * from TABLE where qty = ?";
            $stmt = $this->openDb()->prepare($query);
            $stmt->bindValue(1, $qty, PDO::PARAM_INT);
            $stmt->execute();
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            return $rows;
        }    
    ?>
    

    您的 PHP 页面:

    <?php 
    require "dbc.php";
    
    $getList = $db->getAllData(25);
    
    foreach ($getList as $key=> $row) {
             echo $row['columnName'] .' key: '. $key;
        }
    

    返回结果后您的连接将立即关闭

    【讨论】:

      【解决方案3】:

      根据docs当你调用exit时:

      终止脚本的执行。即使调用了 exit,关闭函数和对象析构函数也将始终执行。

      这意味着您的 PDO 连接将被关闭。不过,最好自己关闭它。

      【讨论】:

        猜你喜欢
        • 2010-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        • 2019-07-20
        • 1970-01-01
        相关资源
        最近更新 更多