开发者

Should I Place My MySQL Database Connection Inside A PHP Function?

Is it safe to place my MySQL Database Connection inside a PHP Function so that other PHP functions can use 开发者_JS百科it?


Yes. it is a good idea.

I even place mine in a class.

class database {

     protected $databaseLink;

     function __construct($mysql_db, $mysql_user, $mysql_pass, $mysql_dbName){
            $this->databaseName = $mysql_dbName;
            $this->database = $mysql_db;
            $this->mysql_user = $mysql_user;
            $this->mysql_pass = $mysql_pass;
            $this->openConnection();
      }

      function openConnection(){
            $this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
            mysql_select_db($this->databaseName, $this->databaseLink);
      }

      function get_link(){
            return $this->databaseLink;
      }

}

Then you can just do:

 $db = new database('database', 'username', 'password', 'dbName');

 //to do a query:
 mysql_query("some query", $db->get_link());


You probably don't want to create it in a regular PHP function. If you will have multiple other functions accessing the db connection in the same script, remember that if you do something like

function get_db()
{
  $db = mysql_connect(...);
  return $db;
}

Then each time you call it, you will be creating and returning a new connection. It may be better to create it once per script inside a class as a Singleton, and have a class method return the database one connection to any function that calls it.

EDIT Neal's answer actually demonstrates the singleton pattern for this nicely. Beat me to it with a more code-complete answer.


It is a good thing for performance. Connecting to the database just when the function was called it will result a good performance for SQL server.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜