Php - mysqli connect to db several times

134 views Asked by At

I have an MVC framework that works like this:

/models/Mo_Sql.php (contains the connectdb function)
/models/Mo_ClassName1.php (that extends Mo_Sql)
/models/Mo_ClassName2.php (that extends Mo_Sql)
/models/Mo_ClassName...X.php (that extends Mo_Sql)
/models/... 

/rules/Ru_ClassName1.php (with private Mo_ClassName1)
/rules/Ru_ClassName2.php (with private Mo_ClassName2)
/rules/Ru_ClassName...X.php (with private Mo_ClassNameX)
/rules/Ru_......

/config/config.php with all Mo_ and Ru_ included and is called in every page of my site.

The concern that I have is that when i require_once config.php, this latter includes N Mo_ files and N Ru_ files, therefore upon construction, I believe there will be multiple db connections opened as every Mo_ file extend Mo_Sql.

My question : is it dangerous to proceed like this? Is there another way to call only once Mo_SQL and/or Mo_Sql->connectdb?

Thanks for your help

1

There are 1 answers

1
Viridis On BEST ANSWER

As Daniel stated, ideally you want a central point in your MVC that handles your database connections. This way it is accessibly in your entire project, plus you can easily keep track of how many connections are running at a time (preferably just one of course).

If you happen to be using a framework, look for a premade library that does these kinds of things. Most recent frameworks have something to handle this.

If you're just creating your own project in native PHP then you can just implement something that behaves like Daniel described.