| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- <?php
- class Database {
- private $host;
- private $db_name;
- private $username;
- private $password;
- public $conn;
- public function __construct() {
- // Load local environment file for development
- $envFile = __DIR__ . '/../.env.local';
- if (file_exists($envFile)) {
- $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- foreach ($lines as $line) {
- if (strpos($line, '=') !== false) {
- list($key, $value) = explode('=', $line, 2);
- putenv("$key=$value");
- }
- }
- }
-
- $this->host = getenv('DB_HOST') ?: 'localhost';
- $this->db_name = getenv('DB_NAME') ?: 'inventory_db';
- $this->username = getenv('DB_USER') ?: 'root';
- $this->password = getenv('DB_PASS') ?: '';
- }
- public function getConnection() {
- $this->conn = null;
- try {
- $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=utf8mb4";
- $this->conn = new PDO($dsn, $this->username, $this->password);
- $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $this->conn->exec("set names utf8");
- } catch(PDOException $exception) {
- error_log("Database connection error: " . $exception->getMessage());
- throw new Exception("Database connection failed");
- }
- return $this->conn;
- }
- }
- ?>
|