Page 1 of 1

Re-Connecting to the database in every function

Posted: Mon Feb 08, 2010 9:52 pm
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.

Re: Re-Connecting to the database in every function

Posted: Tue Feb 09, 2010 1:27 am
by klevis miho
The best way is to have a file connection.php and to include it just on the index.php

Re: Re-Connecting to the database in every function

Posted: Tue Feb 09, 2010 11:53 am
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?

Re: Re-Connecting to the database in every function

Posted: Tue Feb 09, 2010 2:29 pm
by klevis miho
Yes include it just once on the index.php in the beginning, then include the functions.

Re: Re-Connecting to the database in every function

Posted: Tue Feb 09, 2010 3:10 pm
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).