database.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // Load local environment file for development
  10. $envFile = __DIR__ . '/../.env.local';
  11. if (file_exists($envFile)) {
  12. $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  13. foreach ($lines as $line) {
  14. if (strpos($line, '=') !== false) {
  15. list($key, $value) = explode('=', $line, 2);
  16. putenv("$key=$value");
  17. }
  18. }
  19. }
  20. $this->host = getenv('DB_HOST') ?: 'localhost';
  21. $this->db_name = getenv('DB_NAME') ?: 'inventory_db';
  22. $this->username = getenv('DB_USER') ?: 'root';
  23. $this->password = getenv('DB_PASS') ?: '';
  24. }
  25. public function getConnection() {
  26. $this->conn = null;
  27. try {
  28. $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=utf8mb4";
  29. $this->conn = new PDO($dsn, $this->username, $this->password);
  30. $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  31. $this->conn->exec("set names utf8");
  32. } catch(PDOException $exception) {
  33. error_log("Database connection error: " . $exception->getMessage());
  34. throw new Exception("Database connection failed");
  35. }
  36. return $this->conn;
  37. }
  38. }
  39. ?>