nhance/app/Libraries/DataServiceSqlite.php
2024-09-13 09:00:09 +05:30

90 lines
2.6 KiB
PHP
Executable File

<?php
namespace App\Libraries;
use PDO;
class DataServiceSqlite
{
protected $sqliteDb;
public function __construct()
{
$dbPath = WRITEPATH . 'logs/sqlite.db';
try {
$this->sqliteDb = new PDO('sqlite:' . $dbPath);
$this->sqliteDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->createDefaultTable();
} catch (\PDOException $e) {
// Database doesn't exist, create it
log_message('error', 'SQLite DB not found: ' . $e->getMessage());
try {
log_message('error', 'Creating SQLite DB: ');
$this->sqliteDb = new PDO('sqlite:' . $dbPath);
$this->sqliteDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Create default table
$this->createDefaultTable();
log_message('error', 'Creating SQLite DB doné');
} catch (\PDOException $e) {
log_message('error', 'Failed to create SQLite database: ' . $e->getMessage());
throw $e; // Re-throw to allow for further handling
}
}
}
// ... other methods ...
protected function createDefaultTable()
{
$sql = "CREATE TABLE IF NOT EXISTS http (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uuid TEXT,
ip TEXT,
platform TEXT,
browser TEXT,
method TEXT,
endpoint TEXT,
getparams TEXT,
postparams TEXT,
createdon DATETIME DEFAULT CURRENT_TIMESTAMP
)";
$this->sqliteDb->exec($sql);
$sql = "CREATE TABLE IF NOT EXISTS log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
context TEXT,
uuid TEXT,
msg TEXT,
createdon DATETIME DEFAULT CURRENT_TIMESTAMP
)";
$this->sqliteDb->exec($sql);
}
public function insertData(array $data, string $tableName): bool
{
log_message('error', 'SQLite insert called: ');
unset($data['context']);
$columns = implode(', ', array_keys($data));
// print_r($columns);
$placeholders = implode(', ', array_fill(0, count($data), '?'));
$sql = "INSERT INTO $tableName ($columns) VALUES ($placeholders)";
try {
$stmt = $this->sqliteDb->prepare($sql);
$stmt->execute(array_values($data));
return true;
} catch (\PDOException $e) {
log_message('error', 'SQLite insert failed: ' . $e->getMessage());
return false;
}
}
}