105 lines
3.1 KiB
PHP
105 lines
3.1 KiB
PHP
<?php
|
|
class Database {
|
|
private $host;
|
|
private $port;
|
|
private $db_name;
|
|
private $username;
|
|
private $password;
|
|
public $conn;
|
|
|
|
public function __construct() {
|
|
// Load environment variables dari file .env
|
|
$this->loadEnv();
|
|
}
|
|
|
|
/**
|
|
* Load environment variables dari file .env
|
|
*/
|
|
private function loadEnv() {
|
|
$envFile = dirname(__DIR__) . '/.env';
|
|
|
|
if (!file_exists($envFile)) {
|
|
// Jika .env tidak ada, coba copy dari .env.example
|
|
$envExample = dirname(__DIR__) . '/.env.example';
|
|
if (file_exists($envExample)) {
|
|
copy($envExample, $envFile);
|
|
} else {
|
|
die('File .env tidak ditemukan! Silakan buat file .env berdasarkan .env.example');
|
|
}
|
|
}
|
|
|
|
// Baca file .env
|
|
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
$env = [];
|
|
|
|
foreach ($lines as $line) {
|
|
// Skip komentar
|
|
if (strpos(trim($line), '#') === 0) {
|
|
continue;
|
|
}
|
|
|
|
// Parse key=value
|
|
if (strpos($line, '=') !== false) {
|
|
list($key, $value) = explode('=', $line, 2);
|
|
$key = trim($key);
|
|
$value = trim($value);
|
|
$value = trim($value, '"\'');
|
|
$env[$key] = $value;
|
|
}
|
|
}
|
|
|
|
// Set database configuration
|
|
$this->host = $env['DB_HOST'] ?? 'localhost';
|
|
$this->port = $env['DB_PORT'] ?? '3306';
|
|
$this->db_name = $env['DB_NAME'] ?? 'spbu_db';
|
|
$this->username = $env['DB_USER'] ?? 'root';
|
|
$this->password = $env['DB_PASSWORD'] ?? '';
|
|
}
|
|
|
|
/**
|
|
* Get database connection
|
|
*/
|
|
public function getConnection() {
|
|
$this->conn = null;
|
|
try {
|
|
$dsn = "mysql:host=" . $this->host . ";port=" . $this->port . ";dbname=" . $this->db_name;
|
|
|
|
$this->conn = new PDO(
|
|
$dsn,
|
|
$this->username,
|
|
$this->password,
|
|
array(
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
|
|
)
|
|
);
|
|
} catch(PDOException $e) {
|
|
// Log error daripada menampilkannya (untuk production)
|
|
error_log("Database Connection Error: " . $e->getMessage());
|
|
|
|
// Untuk development, tampilkan error
|
|
if ($this->isDevelopment()) {
|
|
die("Connection error: " . $e->getMessage());
|
|
} else {
|
|
die("Database connection failed. Please try again later.");
|
|
}
|
|
}
|
|
return $this->conn;
|
|
}
|
|
|
|
/**
|
|
* Check if running in development mode
|
|
*/
|
|
private function isDevelopment() {
|
|
return true; // Set false untuk production
|
|
}
|
|
|
|
/**
|
|
* Get environment value
|
|
*/
|
|
public function getEnv($key, $default = null) {
|
|
return $this->$key ?? $default;
|
|
}
|
|
}
|
|
?>
|