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
Show parent comment
0
u/fdiengdoh Jun 09 '26
Max allowed is 350 it hit limit only once like 2 days ago. Not a daily thing.