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

Show parent comment

2

u/fdiengdoh Jun 09 '26 edited Jun 09 '26

I realise my main script would call various models such as
$post = new postController();

$category = new categoryController();

$comment = new commentController();

and each model would call Database which my original Database model return a new connection. I have read about dependency injection but still not fully understood it. Will take a look at it. Seems, for now this gemini script would reuse the same connection even if I call various models as above.

I think I might need to update my models to accept something like this instead:

$pdo = Database::getConnection();
$model = new Model($pdo);

6

u/equilni Jun 09 '26

I have read about dependency injection but still not fully understood it.

I think I might need to update my models to accept something like this instead:

That's dependency injection.

Think of it another way, as u/colshrapnel noted passing the DB class instance into models as a parameter.

// Procedural
function getPlayerByUsername(\mysqli $db, string $username) {
    return $db->execute_query(
        'SELECT * FROM players WHERE Username = ?',
        [$username]
    )->fetch_assoc();
}

// Class/OOP
class PlayerDatabase {
    public function __construct(private \mysqli $db) {} 

    public function getByUsername(string $username) {
        return $this->db->execute_query(
            'SELECT * FROM players WHERE Username = ?',
            [$username]
        )->fetch_assoc();
    }
    Other methods
}

And being fair, you don't need a dedicated database class either. Create the PDO instance and pass it.

$pdo = new PDO(....);  
$postDB = new PostDB($pdo);
$categoryDB = new CategoryDB($pdo);
$commentDB = new CommentDB($pdo);

3

u/fdiengdoh Jun 09 '26

thanks for the tips.