database.php 1019 B

1234567891011121314151617181920212223242526272829303132
  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. $this->host = getenv('DB_HOST') ?: 'localhost';
  10. $this->db_name = getenv('DB_NAME') ?: 'inventory_db';
  11. $this->username = getenv('DB_USER') ?: 'root';
  12. $this->password = getenv('DB_PASS') ?: '';
  13. }
  14. public function getConnection() {
  15. $this->conn = null;
  16. try {
  17. $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=utf8mb4";
  18. $this->conn = new PDO($dsn, $this->username, $this->password);
  19. $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  20. $this->conn->exec("set names utf8");
  21. } catch(PDOException $exception) {
  22. error_log("Database connection error: " . $exception->getMessage());
  23. throw new Exception("Database connection failed");
  24. }
  25. return $this->conn;
  26. }
  27. }
  28. ?>