host = getenv('DB_HOST'); $this->db_name = getenv('DB_NAME'); $this->username = getenv('DB_USER'); $this->password = getenv('DB_PASS'); // Debug: Log environment variables (remove in production) error_log("Database config - Host: " . ($this->host ?: 'NOT SET') . ", DB: " . ($this->db_name ?: 'NOT SET') . ", User: " . ($this->username ?: 'NOT SET')); } public function getConnection() { $this->conn = null; // Validate required database configuration if (empty($this->host) || empty($this->db_name) || empty($this->username)) { error_log("Database configuration missing: Host=" . ($this->host ?: 'MISSING') . ", DB=" . ($this->db_name ?: 'MISSING') . ", User=" . ($this->username ?: 'MISSING')); throw new Exception("Database configuration is incomplete. Please check environment variables."); } try { $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=utf8mb4"; error_log("Attempting database connection: $dsn with user " . $this->username); $this->conn = new PDO($dsn, $this->username, $this->password); $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->conn->exec("set names utf8"); error_log("Database connection successful"); } catch(PDOException $exception) { error_log("Database connection error: " . $exception->getMessage()); error_log("Connection details - Host: " . $this->host . ", DB: " . $this->db_name . ", User: " . $this->username); throw new Exception("Database connection failed: " . $exception->getMessage()); } return $this->conn; } } ?>