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-Connecting to the database in every function
Moderator: General Moderators
-
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
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
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
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
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......
Then, anytime you need your database you can just do Then $database would have your script's connection and all the functions of your database class (or whatever you use).
Code: Select all
class DB
{
public static function &getDB()
{
static $instance;
if (!is_object($instance))
{
$instance = //your db connection here
}
return $instance;
}
}Code: Select all
$database =& DB::getDB();