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
0
u/-goldenboi69- Jun 09 '26
I think it's a configuration thing more than a code thing. It's been a few years since I used mysql though.
Unless your do a lot of db stuff during one session in your app your code won't matter since as soon as the page is rendered that connection you open will be closed.
Google the error you get and look at config suggestions.