简体   繁体   English

PHP - 有多个连接时连接数据库的最佳方法

[英]PHP - Best way to connect to database when there are multiple connections

I have just recently acquired the service side of a medium size project. 我刚刚收购了中型项目的服务方面。 The former developer has all of his functions as separate php scripts instead of classes (func1.php, func2.php, etc)... All these 'functions' make a reference to mysqli_connect via referencing the actual 'databaseonnection.php' file. 前开发人员将他的所有功能都作为单独的php脚本而不是类(func1.php,func2.php等)...所有这些'函数'通过引用实际的'databaseonnection.php'文件来引用mysqli_connect This is creating a new connection every time any of the scripts run (every time I have to call a function) and I don't want to do that. 这是每次运行任何脚本时创建一个新连接(每次我必须调用一个函数),我不想这样做。 I was thinking about having a persistent connection, but I'm worried about it getting out of hands as the project is growing more and more every day. 我正在考虑建立一个持久的连接,但我担心它会失控,因为项目每天都在增长。 So, has anyone ever encountered a similar situation? 那么,有没有人遇到类似的情况? What is the best way to handle my connection to the database? 处理我与数据库的连接的最佳方法是什么? Any suggestions would be greatly appreciated. 任何建议将不胜感激。

From the docs for mysql_connect . 来自mysql_connect的文档。 If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. 如果使用相同的参数对mysql_connect()进行第二次调用,则不会建立新的链接,而是返回已打开的链接的链接标识符。

EDIT: I'm sorry I thought you wanted connectivity help. 编辑:对不起,我以为你想要连接帮助。 There is no way except to move all those "functions" into one file where the connection is for them only. 除了将所有这些“函数”移动到一个只连接它们的文件中之外没有办法。

I create a con.php file where my PDO connection is established then include that file anywhere you wish to use a connection Here is the base for a PDO connection: 我创建了一个con.php文件,其中建立了我的PDO连接,然后在您希望使用连接的任何地方包含该文件以下是PDO连接的基础:

$PDO = new PDO("mysql:host=localhost;dbname=dbname", "user_name", "password");

Here is my notes on using the PDO object to make prepared queries. 以下是关于使用PDO对象进行准备查询的说明。 There is more than you need below but good luck. 下面有你需要的东西,但祝你好运。

Within your PHP file that needs a connection: 1: include('con.php'); 在需要连接的PHP文件中:1:include('con.php');

2:  $datas = $PDO->prepare(SELECT * FROM table WHERE title LIKE :searchquery);
    // prepare method creates and returns a PDOstatment object ( print_r($datas); ) which contains an execute() method
    // PDOstatment object has its own methods ie. rowCount()

    // $datas->bindValue(':search', '% . $search . %', )
    // Optional - Manually bind value. see http://php.net/manual/en/pdostatement.bindparam.php

3: $datas->execute( array(':searchquery' => $searchquery . '%'));
    // pass in values that need to be bound AND EXECUTE.

    // There are 17 ways to "fetch" data with the PDO object.
4: $datas-fetchALL(PDO::FETCH_OBJ);

close a pdo connection by the handle: 通过句柄关闭pdo连接:

$PDO = null;

I think you'll be much better off using PDO as opposed to the old MYSQL functions eg mysql_connect . 我认为使用PDO会比使用旧的MYSQL函数(例如mysql_connect好得多。 It's much more robust an interface. 它的界面更加强大。

Below is the basic code to do this: 以下是执行此操作的基本代码:

$db_handle = new PDO("mysql:host=".$db_host.";dbname=".$db_name.";port=".$db_port."", $db_username, $db_password, $connect_options);

where $db_handle is the PDO object representing the database connection, $db_host is your hostname [usually localhost], $db_name is the name of your database, $db_port is the database port number [usually 3306], $db_username and $db_password are your database user access credentials, and $connect_options are optional driver-specific connection options. 其中$db_handle是表示数据库连接的PDO对象, $db_host是您的主机名[通常是localhost], $db_name是数据库的名称, $db_port是数据库端口号[通常为3306], $db_username$db_password是您的数据库用户访问凭据, $connect_options是可选的驱动程序特定的连接选项。

To enable persistent connections you need to set the driver-specific connection option for it before opening the connection: $connect_options = array(PDO::ATTR_PERSISTENT => true); 要启用持久连接,您需要在打开连接之前为其设置特定于驱动程序的连接选项: $connect_options = array(PDO::ATTR_PERSISTENT => true); then execute the earlier database connection code. 然后执行早期的数据库连接代码。

You can get more information on this from the PHP Docs here: http://www.php.net/manual/en/pdo.construct.php and http://php.net/manual/en/pdo.connections.php . 您可以从PHP Docs获取有关此内容的更多信息: http//www.php.net/manual/en/pdo.construct.phphttp://php.net/manual/en/pdo.connections.php

Regarding creating persistent connections, I would suggest that you close every database connection you open at the end of your script (after all your database operations of course) by nullifying your database handle: $db_handle = NULL; 关于创建持久连接,我建议您通过使数据库句柄无效来关闭在脚本末尾打开的每个数据库连接(在所有数据库操作之后): $db_handle = NULL; . You should do this whether you opened a persistent connection or not. 无论是否打开持久连接,都应该这样做。 It sounds counter-intuitive, but I believe you should free up any database resources when your script is done. 这听起来有点违反直觉,但我相信你应该在脚本完成后释放任何数据库资源。

The performance disadvantages of doing this [from my experience] are neglible for most applications. 根据我的经验,这样做的性能缺点对大多数应用来说都是微不足道的。 This is obviously an arguable assertion and you may also find the following link helpful in further clarifying your strategy in this regard: 这显然是一个有争议的断言,您可能还会发现以下链接有助于进一步阐明您在这方面的策略:

Persistent DB Connections - Yea or Nay? 持久数据库连接 - 是或否?

Happy coding! 快乐的编码!

if you have very complex project and need big budget to re-design, and prefer very simple alteration then 如果你有非常复杂的项目,需要很大的预算来重新设计,那么更喜欢非常简单的改造

1) stay in mysqli_connect 2) move the database connection to header of your script. 1)留在mysqli_connect 2)将数据库连接移动到脚本的标题。 3) remove the function databse close() on that functions. 3)删除该函数上的函数数据库close()。 4) remove the connection link variables, it wont needed for single database. 4)删除连接链接变量,单个数据库不需要它。 5) close the database on end of footer. 5)关闭页脚末尾的数据库。

By this way, database connection establish when starting your script and after all queries, it will be closed on footer. 通过这种方式,数据库连接在启动脚本时建立,在所有查询之后,它将在页脚上关闭。 your server can handle the connections without closing/re-open by using keepalive method. 您的服务器可以使用keepalive方法处理连接而无需关闭/重新打开。 basically default keepalive value is 30 to 90 seconds. 基本上默认的keepalive值是30到90秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM