Efficient way to connect to a database when multiple functions are running queries

£可爱£侵袭症+ 提交于 2019-12-23 06:58:29

问题


I'm writing an application that has a functions.php file that a javascript file is accessing via Ajax. Currently I have each function connecting to the database, running queries, then closing the database. I know there has to be a more efficient way of doing this. I'd like to only input the database credentials once and then have all the functions use it. Whats the most efficient way to do this? I've read quite a few of the answers here on this topic but they're all different and I'm lost. Just point me in the right direction :)

Currently my functions are opening the database like this.

$db = new mysqli("hostname", "username", "password");
$db -> select_db("database name");

Or like this

mysql_connect("hostname", "username", "password");
mysql_select_db('database name') or die( "Unable to select database");

回答1:


You can just check whether the database connection variable is already set:

if (!isset($db)) {
    $db = new mysqli(...);
    $db->select_db("database_name");
}

and similarly with mysql_connect (it returns a connection resource, so you can assign it to a variable, even though it's an optional argument to the other functions).

Another way is to use a function with a static variable:

function connect_db() {
    static $db = new mysqli(...);
    static $selected = $db->select_db("database_name");
    return $db;
}

A third options is to connect to the database once at the beginning of the script, instead of in each function. Then either pass $db to each function, or access it with global $db;.




回答2:


The simple answer is connection pooling. A connection pool is a pool of connections that are always connected to the database. You can set a high water mark and a low water mark for the number of connections.

When your application requests a connection from the pool it will then use one of the idle connections and reuse it. This is how you scale database connectivity.

You are using PHP so look at the following:

  1. http://www.oracle.com/technetwork/topics/php/php-scalability-ha-twp-128842.pdf
  2. http://php.net/manual/en/mysqlnd-ms.pooling.php

There is a lot of information around this on the net.



来源:https://stackoverflow.com/questions/18264415/efficient-way-to-connect-to-a-database-when-multiple-functions-are-running-queri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!