开发者

Open and close SQL for each function, or open SQL do everything then close SQL?

I was wondering what is the best practice for PHP/MySQL development.

For example, I have the following:

  • connect.php
  • close.php

In connect.php, it uses require_once('classes/database.php') a开发者_StackOverflow社区nd uses $database = new database(); then calls $database->connect();

Should I require_once these into say a header.php and a footer.php and have an overall connection (every main webpage includes these), or, instead open and close it for when I need it. For example I have a functions.php file that has functions which should I do:

public function test() {
    $db = new database();
    // db setup here
    $db->connect();
    // do stuff here
    $db->disconnect();
}

or

public function test() {
    // stuff here
}

Thanks!


Connecting to a database is typically a fairly expensive process - time-consuming. Avoid connecting multiple times in response to a single request if at all possible.


Opening a connection to database usually takes some time, so I'll advise to open it once and for all in the beginning of the script.

It is also good to know that at the end of the script, PHP automatically close open connection, so there is normally no need to explicitly close a connection to a database.

In order to have the more robust code, I'll do something like this :

class Database {
    var $connection = null;

    public function connect() {
        if($this->connection == null) {
            // setup the connection here
        }
    }
}

This way, each time you need a database connection you can call $db->connect() but the work will be actually done only on the first call. This will assure that even after a code refactoring, say in your header file, database will be connected when needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜