mysqli connections

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Is new connection created every time I call to mysqli_connect with the
same connection parameters in the same script?


$db1 = mysqli_connect('host', 'user', 'pass');


$db2 = mysqli_connect('host', 'user', 'pass');

Notice the same connection parameters. In another words is PHP engine
smart enough to see that I'm trying to create connection that already


Re: mysqli connections

Ralphz schreef:
Quoted text here. Click to load it

Accoring to the manual it is not doing that.
"open a NEW connection to the MySQL server"


why do you want this?

if you want this you can do:

if (!$db1) {
    $db2 = mysqli_connect('host', 'user', 'pass');
} else {
    $db2 = $db1;


Re: mysqli connections

Luuk wrote:
Quoted text here. Click to load it


Thank you for your response.

The thing is that i don't know how many different database connections I
will have when the application goes to production. Right now I have many
classes that take instantiated database object as one of the constructor
parameters and uses it to do all data manipulation.

The problem arises with classes that aggregate few other classes. Now I
have to come up with some nice way to tell this class how to create
objects it is going to use to manipulate data in database.

I can pass to the constructor array of already instantiated DB objects
but that forces me to create connections before I create 'aggregate'
object. I would like to implement it in a way that when i create object
it creates all needed objects transparently using database connection
settings form the configuration file. But now I'm not sure if I'm not
creating multiple connections to the DB. I don't want all lets say 5
classes to go establishing  their own DB connections if there is already
one created by come other class. As far as I know establishing database
connection is very time consuming.

I hope I explained my problem well enough :P


Re: mysqli connections

Ralphz wrote:
Quoted text here. Click to load it

You want a singleton for your database object.  It solves a lot of
problems like this.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Re: mysqli connections

Jerry Stuckle wrote:

Quoted text here. Click to load it

Thank you!

I think that's what I was looking for. Actually in my situation mix of
singleton pattern and factory class will be the best way to go.

Factory class would check if we already have connection with the
parameters specified by script and then return already existing instance
of an object or create one.


Site Timeline