Forum Moderators: coopster

Message Too Old, No Replies

How to avoid double db access connection

         

impact

12:30 pm on Aug 10, 2011 (gmt 0)

10+ Year Member



Dear,

I have my users timezone stored in the database. To access timezone I have a separate class which returns users timezone in various format.

In the timezone class I have two distinct functions for retrieving users timezone from the database. One of the function have database access and the other function dont have db access.

Some times when I want to get the users timezone with in a function from another class, which already have an open db connection I use the function in timezone class which does not have the db access.

Some times when I want to get the users timezone with in a function from another class, which does not already have an open db connection I use the function in timezone class which can create the db connection.

The reason why I do this is to avoid the creation of double db access connection.

Now my question is, am I correct in my thinking? or wrong because, with in an instance of a script once db access has been created the PHP engine wont allow another new connection with in the same function

I am novice and still trying to understand the fundamentals of good PHP programming.

Your help will be appreciated.

Thank you.

brotherhood of LAN

1:02 pm on Aug 10, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You just need one database connection that you can include somewhere near the start of your script, and that connection will be universally available for the remainder of the script.

When you don't specify a resource with mysql_connect(), the last known connection is used, and since you only need one connection you don't need to reference the resource.

See: [php.net...]

If you were to connect to two different databases, e.g. with a new user/password on the same database or a database on another server, then that is when you will likely need to keep an eye on which database connection is being used.

coopster

10:44 pm on Aug 12, 2011 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You can also use a factory pattern or a singleton instance of a database class. Google either for more information or read more on the PHP manual page:
[php.net...]