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 {
private static ?PDO $connection = null;
public static function getConnection(): PDO {
if (self::$connection !== null) {
return self::$connection;
}
$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";
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;
}
public static function closeConnection(): void {
self::$connection = null;
}
}
Edit: Ignore the \ as somehow reddit added these when I paste the code.
View all comments
2
u/colshrapnel Jun 09 '26
See, this code would only help if your current code is really messed up, that is, making multiple connections from the same script/request. In case you are starting just a single connection at the beginning, and then use it for all database interactions, as you should, this code won't help you at all. If this error would appear again, it means some other problem that needs to be investigated.
And if each model indeed opens its own connection (probably because inheriting from the DB class, despite the fact that a model is not a database in any possible way) you can use this shortcut Gemini wrote or make it proper dependency injection, passing the DB class instance into models as a parameter.