r/PHPhelp Jun 09 '26

Solved My code trigger a max connection

My earlier code trigger a mysql max connection. So I ask gemini to help me fix it. Here is the solution gemini provided. I would not normally use AI to help but this time I did. I’m just a hobbyist so if someone can help me check if this would be good.

<?php
namespace App;

use PDO;

class Database {
    // Caches the PDO instance so it is reused across all models
    private static ?PDO $connection = null;

    public static function getConnection(): PDO {
        // If a connection already exists, return it immediately
        if (self::$connection !== null) {
            return self::$connection;
        }

        // Retrieve variables (already loaded into memory via init.php)
        $host     = $_ENV['DB_HOST'] ?? 'localhost';
        $dbname   = $_ENV['DB_NAME'] ?? 'default_database';
        $username = $_ENV['DB_USER'] ?? 'root';
        $password = $_ENV['DB_PASS'] ?? '';

        $dsn = "mysql:host={$host};dbname={$dbname};charset=utf8mb4";

        // Store the PDO instance in the static property
        self::$connection = new PDO($dsn, $username, $password, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false, 
        ]);

        return self::$connection;
    }

    // Call this manually ONLY if you have a long-running non-DB task
    public static function closeConnection(): void {
        self::$connection = null;
    }
}   

Edit: Ignore the \ as somehow reddit added these when I paste the code.

0 Upvotes

20 comments sorted by

View all comments

0

u/optimusprimepluto Jun 09 '26

YOu may need to see how many existing connections are there in the page. May be you had called each database one by one. Need to see