简体   繁体   English

用php与mysql数据库建立多个连接

[英]Multiple connections to mysql database with php

Let's say I call multiple functions on a given page. 假设我在给定页面上调用了多个函数。

function getProfile {
    <mysql code to connect>
    ...
    ...
}

function getMatchingUsers {
    <mysql code to connect>
    ...
    ...
}

If I call the two functions above on a given page, wouldn't that open multiple connections to the DB? 如果我在给定页面上调用上面的两个函数,那会不会打开与数据库的多个连接? I assume php would automatically close the DB connection after the first function runs, but then it would automatically open another connection for the second function. 我假设php将在第一个函数运行后自动关闭数据库连接,但是随后它将为第二个函数自动打开另一个连接。 My question is, what if my page makes a bunch of calls to the DB. 我的问题是,如果我的页面对数据库进行了大量调用,该怎么办? Is this good for memory, io, etc...? 这对内存,IO等有用吗?

Why not use some form of connection pooling. 为什么不使用某种形式的连接池。 That way the pool maintains a set of connections, and your app is merely taking connections from the pool and returning them. 这样,池将维护一组连接,而您的应用程序仅从池中获取连接并返回它们。 The pool looks after opening and closing as required (and maintains a set of open connections). 池将根据需要查看打开和关闭的情况(并维护一组打开的连接)。

This SO answer covers more options wrt. 这样的答案涵盖了更多的选择。 PHP and connection pooling. PHP和连接池。

The simplest way is to make the connection at the beginning of your script. 最简单的方法是在脚本的开头进行连接。 The mysql functions will use the last open connection to do their work, so there is no need to connect inside each function. mysql函数将使用最后打开的连接来完成其工作,因此不需要在每个函数内部进行连接。

//Start of your file
mysql_connect()


function a(){
// no connect here, just use mysql
mysql_query($sql)
}

function b(){
// no connect here, just use mysql
mysql_query($sql)
}

Try to use 1 connection if you are conneciting to the same mysql server. 如果您要连接到同一个mysql服务器,请尝试使用1个连接。

$host = "localhost";
$user = "user";
$pass = "password";
$database = "dbname";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");

Note that you have a $linkID and that's what you use to reference it. 请注意,您有一个$ linkID,这就是引用它的用途。 Make a connection specific query like this: 进行特定于连接的查询,如下所示:

$resultID = mysql_query($query, $linkID) or die("Data not found.");

When you are finished, close that specific connection 完成后,关闭该特定连接

mysql_close($linkID)

If you have more than 1 mysql sever addresses, then use a separate reference like $linkID2 如果您有多个mysql服务器地址,请使用单独的引用,例如$ linkID2

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

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