database.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. class Database {
  3. private $host;
  4. private $db_name;
  5. private $username;
  6. private $password;
  7. public $conn;
  8. public function __construct() {
  9. // In Docker, environment variables are passed directly
  10. // For local development, try to load .env.local file
  11. $envFile = __DIR__ . '/../.env.local';
  12. if (file_exists($envFile)) {
  13. $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  14. foreach ($lines as $line) {
  15. if (strpos($line, '=') !== false) {
  16. list($key, $value) = explode('=', $line, 2);
  17. putenv("$key=$value");
  18. }
  19. }
  20. }
  21. // Get database configuration from environment variables
  22. $this->host = getenv('DB_HOST');
  23. $this->db_name = getenv('DB_NAME');
  24. $this->username = getenv('DB_USER');
  25. $this->password = getenv('DB_PASS');
  26. // Debug: Log environment variables (remove in production)
  27. error_log("Database config - Host: " . ($this->host ?: 'NOT SET') .
  28. ", DB: " . ($this->db_name ?: 'NOT SET') .
  29. ", User: " . ($this->username ?: 'NOT SET'));
  30. }
  31. public function getConnection() {
  32. $this->conn = null;
  33. // Validate required database configuration
  34. if (empty($this->host) || empty($this->db_name) || empty($this->username)) {
  35. error_log("Database configuration missing: Host=" . ($this->host ?: 'MISSING') .
  36. ", DB=" . ($this->db_name ?: 'MISSING') .
  37. ", User=" . ($this->username ?: 'MISSING'));
  38. throw new Exception("Database configuration is incomplete. Please check environment variables.");
  39. }
  40. try {
  41. $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=utf8mb4";
  42. error_log("Attempting database connection: $dsn with user " . $this->username);
  43. $this->conn = new PDO($dsn, $this->username, $this->password);
  44. $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  45. $this->conn->exec("set names utf8");
  46. error_log("Database connection successful");
  47. } catch(PDOException $exception) {
  48. error_log("Database connection error: " . $exception->getMessage());
  49. error_log("Connection details - Host: " . $this->host . ", DB: " . $this->db_name . ", User: " . $this->username);
  50. throw new Exception("Database connection failed: " . $exception->getMessage());
  51. }
  52. return $this->conn;
  53. }
  54. }
  55. ?>