Files
territory-assigner/db.php
2025-12-06 18:23:43 +01:00

85 lines
2.4 KiB
PHP

<?php
/**
* Gestione Connessione Database
* Territory Manager
*/
require_once 'config.php';
class Database {
private static $instance = null;
private $connection;
private function __construct() {
try {
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->connection = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (PDOException $e) {
die("Errore di connessione al database: " . $e->getMessage());
}
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
// Metodo helper per query semplici
public function query($sql, $params = []) {
try {
$stmt = $this->connection->prepare($sql);
$stmt->execute($params);
return $stmt;
} catch (PDOException $e) {
error_log("Errore query: " . $e->getMessage());
return false;
}
}
// Metodo helper per ottenere una singola riga
public function fetchOne($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt ? $stmt->fetch() : null;
}
// Metodo helper per ottenere tutte le righe
public function fetchAll($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt ? $stmt->fetchAll() : [];
}
// Metodo helper per ottenere valore configurazione
public function getConfig($key, $default = null) {
$result = $this->fetchOne(
"SELECT config_value FROM config WHERE config_key = ?",
[$key]
);
return $result ? $result['config_value'] : $default;
}
// Metodo helper per aggiornare configurazione
public function updateConfig($key, $value) {
return $this->query(
"UPDATE config SET config_value = ? WHERE config_key = ?",
[$value, $key]
);
}
}
// Funzione helper globale per ottenere il database
function getDB() {
return Database::getInstance();
}