MySQL关闭时机

时间:2014-07-22 07:22:42

标签: php mysql mysqli

我写了一个类来加载数据并通过MySQLi导出为SMARTY格式

public function myRow($sql)
{
    $this->connect();
    $rec = $this->conn->query($sql);
    $this->recordCount = $rec->num_rows;

    if ($this->makeRecordCount) {
        $this->totalRecordCount = $this->recordCount;
    }

    if ($this->recordCount > 0) {
        $names = array();
        $result = array();
        $temp = array();
        $count = $rec->field_count;

        // Get fields name
        while ($fields = mysqli_fetch_field($rec)) {
            $names[] = $fields->name;
        }

        while ($row = $rec->fetch_assoc()) {
            foreach ($names as $name) {
                $temp[$name] = $row[$name];
            }

            array_push($result, $temp);
        }
    } else {
        $result = null;
    }

    $this->conn->close();

    return $result;
}

然后我可以像

那样
$sql = "SELECT * FROM `table`";
$datas = $class->myRow($sql);
$smarty->assign('datas', $datas);

可能有很多数据需要在一个页面中加载,我只想连接一次数据库,但我想在课堂上做这一切,我不想做像

这样的事情
$class->connect();
$sql = "SELECT * FROM `table`";
$datas = $class->myRow($sql);
$smarty->assign('datas', $datas);

$sql = "SELECT * FROM `table2`";
$datas = $class->myRow($sql);
$smarty->assign('data2s', $data2s);
$class->close();

我觉得它很难看,但如果我在课堂上这样做,那意味着我在每个数据加载时打开和关闭连接,如何更美观?

3 个答案:

答案 0 :(得分:1)

也许我错了,但你不需要强制关闭mysql连接,因为如果连接不是persistent,那么php garbage collector会关闭所有连接脚本执行后。

所以我建议你不要强制关闭mysql,让garbage collector处理这个任务,如果你确定不再需要mysql事务,那么只能自己关闭连接。

答案 1 :(得分:1)

您根本不需要(并且不应该)打开/关闭myRow()功能内的连接。

选项1(天真的方法):在班级处理连接

class MyDAOClass {
    private static $connection = null;

    public function __construct() {
        if (self::$connection === null) {
             // establish connection here
        }
    }

    public function myRow(...) {
        // use self::$connection here
    }
}

选项2:

从类外部处理连接(可能在单例类中),因为应用程序中的所有对象可能共享同一个对象。

答案 2 :(得分:0)

你的第二个建议是我会做的。

$class->connect();
$sql = "SELECT * FROM `table`";
$datas = $class->myRow($sql);
$smarty->assign('datas', $datas);

$sql = "SELECT * FROM `table2`";
$datas = $class->myRow($sql);
$smarty->assign('data2s', $data2s);
$class->close();

您连接到数据库一次。由于PHP是单线程的,您将加载第一个结果,然后立即加载第二个结果。一切都完成后,关闭连接。没有任何连接可以保持比它更长的时间,这很好。

我通常做的是使与Smarty相关联的方法也关闭我的数据库连接。这样我就不用担心关闭它了。

这样的事情:

<?php
// Store reference to Smarty in Class
$class->setSmarty($smarty);

[...]

// Done with all database fetching, now display the template
$class->display('my_template.tpl');

[...]

// Example inplementation of the class
Class YourClass {
    private $smarty;
    public function setSmarty($smarty) {
        $this->smarty = &$smarty;
    }
    public function display($tpl) {
        $this->close();
        $this->smarty->display($tpl);
    }
}
?> 
相关问题