catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.84k stars 1.15k forks source link

Uncaught PDOException: Too many connections #1076

Closed thurinus closed 1 year ago

thurinus commented 1 year ago

Information

Describe the Problem I've been running into intermittent 500 errors on my webhost that seem to be caused by:

PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1040] Too many connections in .../vendor/catfan/medoo/src/Medoo.php:323

Googling suggests that I should increase max-connections in mysql to circumvent that, but I don't think I have that kind of access on my webhost.

Makes me wonder if I'm using Medoo wrong. Basically I have a Utils class that fetches a Medoo instance, returning a cached one if one already exists, or creating/caching a new one if not. Should a new Medoo instance be created for each query instead?

Detail Code This is how I'm currently managing my Medoo instance. Is this the wrong way to do it?

class Utils
{
    private static $mDb;

    public static function getDb()
    {
        if (!self::$mDb) {
            self::$mDb = new Medoo\Medoo([
                'type' => 'mysql',
                'server' => DB_HOST,
                'database' => DB_NAME,
                'username' => DB_USER,
                'password' => DB_PASS
            ]);
        }
        return self::$mDb;
    }
...
}

Expected output No 500 errors stemming from "PDOException: Too many connections".

catfan commented 1 year ago

This is nothing Medoo can control for that. It's up to your database and web server configuration.

You can check out your log file to see what the connection is and which API or PHP file is making too many connections.

You are using the singleton pattern, and there is no problem with your code. But you can also check out your whole framework that how many new Medoo() are fired in a query called. Just keep using one connection for the whole query lifetime is fine.

thurinus commented 1 year ago

The singleton pattern, of course. Must've been exhausted last night heh. Thanks for the quick response. I think I've been diligent with optimization on my side; I'll check with the host to see if anything can be done about it.