I'm still confused on how to solve 'max_user_connections' problem

Thank you for the elaborate post! All the information you’ve provided really helps paint a clear picture for me as to what’s going on. Also, you seem to have a pretty good understanding of what’s going on, which helps a lot.

I think I agree with the StackOverflow post you found. I didn’t know about the persistent option before, but it seems like it keeps the database connection alive even after the request ends.

If I understand correctly how this option is implemented and works with Apache (connections are held by Apache worker processes), I don’t think this option works well at all on our hosting, and may result in a large number of lingering database connections that never get used (but will still use your max_user_connections allocation).

So I think you should definitely turn the persistent connection option off. The ERR_TOO_MANY_REDIRECTS is odd, but it may be unrelated and I think we’ll be able to figure it out.

Yes, I agree that this is not a particularly efficient way to create handle connections, because every instance of UserModel will establish a new database connection.

There are many different ways in which you can try to fix this problem. Using a Service Container is fancy but hard to implement. A simpler approach is to use the Singleton Pattern. Some consider it to be an antipattern, but I think it’s an appropriate amount of complexity for your use case.

You can create a Singleton like this:

If you turn your Database class into a singleton, you could just replace the $this->db = new Database() with $this->db = Database::getInstance(), and easily reuse the same database connection for all models.

7 Likes