Re-Connecting to the database in every function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
YuniYasha
Forum Newbie
Posts: 2
Joined: Mon Feb 08, 2010 9:46 pm

Re-Connecting to the database in every function

Post by YuniYasha »

I've been working on a site and I'm creating quite a few functions in it. All my functions are stored in there own individual files.

For example: On my index page... I call about 4 of those functions.. Each function has a mysqli_connect in it.

So This means I am connecting to my database 5 times.. Once on the index page, and 4 for the 4 functions.

Will this create multiple connections (Guessing it will), and would it drastically reduce the performance of the website? Is this a bad habit? If so, can I just give the Connection to the functions through a argument? (ex: function GetUsernames($dbc))

Ty for any info you can provide on this topic.
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Re-Connecting to the database in every function

Post by klevis miho »

The best way is to have a file connection.php and to include it just on the index.php
YuniYasha
Forum Newbie
Posts: 2
Joined: Mon Feb 08, 2010 9:46 pm

Re: Re-Connecting to the database in every function

Post by YuniYasha »

Yah, I have a fileconnect.php but I am including it into every function. If I were to only include it on the Index page, would all of the functions I include on that page be able to use that same connection?
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Re-Connecting to the database in every function

Post by klevis miho »

Yes include it just once on the index.php in the beginning, then include the functions.
User avatar
JNettles
Forum Contributor
Posts: 228
Joined: Mon Oct 05, 2009 4:09 pm

Re: Re-Connecting to the database in every function

Post by JNettles »

Also, if you're up for an object-oriented solution I'd recommend keeping your connection in a static function which you can access via a factory. Like......

Code: Select all

 
class DB
{
    public static function &getDB()
    {
        static $instance;
 
        if (!is_object($instance))
        {
            $instance = //your db connection here
        }
 
        return $instance;
    }
}
Then, anytime you need your database you can just do

Code: Select all

$database =& DB::getDB();
Then $database would have your script's connection and all the functions of your database class (or whatever you use).
Post Reply