Files
api/classes/db.php
T
2024-12-16 08:54:03 +01:00

106 lines
2.5 KiB
PHP

<?php
namespace classes;
use Exception;
use mysqli;
class db
{
private string $host;
private string $user;
private string $password;
private string $database;
public mysqli $conn;
public function __construct(array $config)
{
$this->host = $config['host'];
$this->user = $config['user'];
$this->password = $config['password'];
$this->database = $config['database'];
}
public function connect(): void
{
global $response;
try {
$this->conn = new mysqli($this->host, $this->user, $this->password, $this->database);
} catch (Exception $e) {
$response->internal_server_error($e->getMessage());
}
}
public function query(string $sql): \mysqli_result|bool
{
// If the connection is not established, connect
return $this->conn->query($sql);
}
public function fetch_assoc($result)
{
return $result->fetch_assoc();
}
public function fetch_all($result)
{
return $result->fetch_all(MYSQLI_ASSOC);
}
public function escape_string(string $string): string
{
return $this->conn->real_escape_string($string);
}
public function close(): void
{
$this->conn->close();
}
public function get(string $table, int $id)
{
$sql = "SELECT * FROM $table WHERE id = $id";
$result = $this->query($sql);
return $this->fetch_assoc($result);
}
public function list_objects(string $table): array
{
$sql = "SELECT * FROM $table";
$result = $this->query($sql);
return $this->fetch_all($result);
}
public function list_objects_paginated(string $table, int $page, int $limit): array
{
$offset = ($page - 1) * $limit;
$sql = "SELECT * FROM $table LIMIT $limit OFFSET $offset";
$result = $this->query($sql);
return $this->fetch_all($result);
}
public function count_objects(string $table): int
{
$sql = "SELECT COUNT(*) FROM $table";
$result = $this->query($sql);
return $result->fetch_row()[0];
}
public function add_object(string $table, array $data): void
{
$columns = implode(', ', array_keys($data));
$values = implode("', '", array_values($data));
$sql = "INSERT INTO $table ($columns) VALUES ('$values')";
$this->query($sql);
}
public function insert_id(): int
{
return $this->conn->insert_id;
}
public function conn(): mysqli
{
return $this->conn;
}
}