1
0
Fork 0
This repository has been archived on 2024-02-17. You can view files and clone it, but cannot push or open issues or pull requests.
Accommodation_Management/src/model.php
2020-12-20 03:56:05 +01:00

71 lines
2 KiB
PHP

<?php
class Model {
protected static $db = null;
public function __construct()
{
$this->initDatabase();
}
public static function initDatabase(){
try {
/*
* Init connection to the DB
*/
Model::$db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
Model::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e){
var_dump($e);
}
}
/*
* GET/SELECT Query
*/
public static function fetch($filters = []): array
{
$query = 'SELECT * FROM ' . get_called_class();
$args = [];
$c = 0;
$output = [];
$_col = get_called_class()::getColumns();
forEach($filters as $filter){
if (is_array($filter) && count($filter) === 3 && array_key_exists($filter[0], $_col) && in_array($filter[1], ['=','<','>','<>','LIKE'])){
if($c === 0){
$query .= ' WHERE';
}else{
$query .= ' AND';
}
$query .= ' ' . $filter[0] . ' ' . $filter[1] . ' ?';
$args[] = $filter[2];
}else{
throw new Exception('Invalid SQL filters');
}
$c++;
}
$q = Model::$db->prepare($query);
$q->execute($args);
$d = $q->fetchAll(PDO::FETCH_ASSOC);
forEach($d as $row){
$class=get_called_class();
$output[] = new $class($row);
}
return $output;
}
protected function getColumns(): array
{
$q = Model::$db->prepare('SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?');
$q->execute(array(get_called_class()));
$d = $q->fetchAll(PDO::FETCH_ASSOC);
$out = [];
forEach($d as $col){
$out[$col['COLUMN_NAME']] = $col;
}
return $out;
}
}
/*
* Load our models
*/
foreach (glob(MODELS_PATH . '/*.php') as $filename)
{
require_once $filename;
}