0

I recently switched from ext/mysql to mysqli in a PHP project. In that project, I extensively used the connection reuse feature of mysql_connect by setting the new_link parameter set to false.

As far as I understand, there is no such mechanism in mysqli_connect; it will always return a new connection even though the same host and user is used. Is this correct? Is there some other function that can mimic the reuse-behaviour?

NB: I see that with prepending the host with p: will create a persistent connection. However, this cannot be used in my case, as part of my project relies on temporary tables.

Update:
The actual mysqli object is embedded in a DB handler class which manages access to the database. This handler is always used to interact with the DB.

I oversimplified my problem because I just wanted to focus on the question if mysqli can automatically reuse a single connection by multiple calls to mysqli_connect with identical parameters. My project is an extenstion to a framework and provides multiple entry points and hooks. I cannot control the order or number of function calles from the hosting framework into my extension. Each part of my extension creates an instance of the DB handler, but could reuse the actual underlying connection.

The creation of the DB handler is done though a db-factory. So I will probabely have to implement some sort of connection-caching there myself...

4

1 回答 1

0

不,mysqli ext 不遵循这种懒惰的 mysql ext 行为,这是有原因的。
因此,您必须始终明确地处理 mysqli 对象。但是,唯一的问题是变量范围。但只要你有$mysqli可见的对象,你就可以使用它。

但是,还有另一个问题:您根本不应该$mysqli在应用程序代码中处理对象。这是旧 mysql ext 的问题,也是 mysqli ext 的问题 -它不打算按原样在应用程序代码中使用。

必须创建某种包装器来封装所有与数据库相关的东西,并且在应用程序代码中始终只使用这个包装器类。

所以,给自己弄一个这样的包装器,创建它的一个实例,然后作为参数传递给每个类和函数。

于 2013-08-28T10:34:37.523 回答