Changed database interaction structures

This commit is contained in:
Gregorio Chiko Putra 2017-09-09 11:21:51 +07:00
parent 1de9cb6447
commit 59d8c11d9b
5 changed files with 499 additions and 296 deletions

View File

@ -10,13 +10,11 @@ use Core\Hash;
class Home
{
public $model,
$table;
public $model;
public function __construct()
{
$this->model = new Access();
$this->table = 'user';
}
/* Routes */
@ -31,6 +29,7 @@ class Home
if (Session::exists('userid')) {
Session::flash('info', 'Anda telah masuk.');
Redirect::to('/');
die();
} else {
View::render('Access/login.html', [
'token' => Token::generate()
@ -75,8 +74,6 @@ class Home
}
}
$table = 'user';
$date = new \DateTime();
$now = $date->format('Y-m-d');
$args['registered_at'] = $now;
@ -89,7 +86,7 @@ class Home
$args['full_name'] = htmlspecialchars($args['full_name']);
$args['username'] = htmlspecialchars($args['username']);
$data = $this->model->showAll($table);
$data = $this->model->showAll();
foreach ($data as $users) {
if ($args['username'] == $users['username']) {
Session::flash('info', 'Username telah digunakan. Silahkan gunakan username lain.');
@ -98,20 +95,21 @@ class Home
}
}
$this->model->entry($table, $args);
$this->model->entry($args);
Redirect::to('/');
die();
}
public function put($args = [])
{
$table = 'user';
$username = $args['username'];
$password = $args['password'];
$user = $this->model->showAll($table, [
$user = $this->model->showAll([
['username', '=', $username]
]);
if ($user == false) {
$info = "Username/password salah.";
} else {
@ -121,11 +119,11 @@ class Home
if ($user['max_user'] <= 0) {
$info = "Telah mencapai maksimal user yang diizinkan. Silahkan logout pada perangkat lain terlebih dahulu.";
} else {
if ($this->model->update($table, ['status' => 1], $user['id']) != true) {
if ($this->model->update(['status' => 1], $user['id']) != true) {
$info = "Terjadi kesalahan. Silahkan coba lagi dalam beberapa saat.";
} else {
$max_user = $user['max_user'] - 1;
if ($this->model->update($table, ['max_user' => $max_user], $user['id']) == true) {
if ($this->model->update(['max_user' => $max_user], $user['id']) == true) {
Session::put('userid', $user['id']);
Session::put('username', $user['username']);
Session::put('full_name', $user['full_name']);
@ -139,20 +137,19 @@ class Home
}
Session::flash('info', $info);
Redirect::to('/');
die();
}
public function delete()
{
$table = 'user';
$userid = Session::get('userid');
$user = $this->model->showAll($table, [
$user = $this->model->showAll([
['id', '=', $userid]
]);
$max_user = $user['max_user'] + 1;
if ($this->model->update(
$table,
[
'status' => 0,
'max_user' => $max_user

View File

@ -10,13 +10,11 @@ use \Core\Redirect;
class Posts
{
private $post,
$table;
private $post;
public function __construct()
{
$this->model = new Post();
$this->table = 'pengumuman';
}
public function checkValid()
@ -24,39 +22,48 @@ class Posts
$date = new \DateTime();
$now = $date->format("Y-m-d");
$valid = $this->model->showAll($this->table, [
$valid = $this->model->showAll([
['valid_at', '<=', $now],
['status', '!=', 3]
]);
if ($valid) {
foreach ($valid as $fields) {
$id = $fields['id'];
$this->model->update($this->table, ['status' => 1], $id);
if (is_array($fields)) {
$id = $fields['id'];
} else {
$id = $valid['id'];
}
$this->model->update(['status' => 1], $id);
}
}
$not_valid = $this->model->showAll($this->table, [
$not_valid = $this->model->showAll([
['valid_at', '>', $now],
['status', '!=', 3]
]);
if ($not_valid) {
foreach ($not_valid as $fields) {
$id = $fields['id'];
$this->model->update($this->table, ['status' => 2], $id);
if (is_array($fields)) {
$id = $fields['id'];
} else {
$id = $not_valid['id'];
}
$this->model->update(['status' => 2], $id);
}
}
$expired = $this->model->showAll($this->table, [
$expired = $this->model->showAll([
['expired_at', '<', $now],
['status', '!=', 3]
]);
if ($expired) {
foreach ($expired as $fields) {
$id = $fields['id'];
$this->model->update($this->table, ['status' => 0], $id);
if (is_array($fields)) {
$id = $fields['id'];
} else {
$id = $expired['id'];
}
$this->model->update(['status' => 0], $id);
}
}
}
@ -66,7 +73,9 @@ class Posts
{
$this->checkValid();
$posts = $this->model->showAll($this->table, [
$posts = [];
$post = $this->model->showAll([
['status', '=', 1]
]);
@ -75,19 +84,21 @@ class Posts
$status = '';
if (Session::exists('userid')) {
$posts = $this->model->showAll($this->table);
$post = $this->model->showAll();
$status = 'admin';
}
for ($i=0; $i < count($posts); $i++) {
$posts[$i]['content'] = preg_replace('/[\r]/', '', $posts[$i]['content']);
$posts[$i]['content'] = preg_replace('/[\n]/', "<br/>", $posts[$i]['content']);
if (array_key_exists(0, $post)) {
$posts = $post;
} else {
$posts[] = $post;
}
View::render($url, [
'posts' => $posts,
'status' => $status
]);
die();
}
public function entry()
@ -96,9 +107,7 @@ class Posts
$date = new \DateTime();
$now = $date->format("Y-m-d");
$this->table = 'kategori';
$categories = $this->model->showAll($this->table);
$categories = $this->model->showAll([], 'kategori');
$user = Session::get('userid');
@ -108,8 +117,6 @@ class Posts
'user' => $user,
'token' => Token::generate()
]);
$this->table = 'pengumuman';
} else {
throw new \Exception("Page not found", 404);
}
@ -123,24 +130,22 @@ class Posts
$id = implode('', $id);
}
$categories = $this->model->showCategories();
$categories = $this->model->showAll([], 'kategori');
$post = $this->model->showAll($this->table, [
$post = $this->model->showAll([
['id', '=', $id]
]);
$creator = $post['creator'];
$editor = $post['editor'];
$this->table = 'user';
$table = 'users';
$creator = $this->model->showAll($this->table, [
$creator = $this->model->showAll([
['id', '=', $creator]
]);
$editor = $this->model->showAll($this->table, [
], $table);
$editor = $this->model->showAll([
['id', '=', $editor]
]);
$this->table = 'pengumuman';
], $table);
$editor_now = Session::get('userid');
@ -168,15 +173,12 @@ class Posts
public function category()
{
if (Session::exists('userid')) {
$this->table = 'kategori';
$categories = $this->model->showAll($this->table);
$categories = $this->model->showAll([], 'kategori');
View::render('Data/kategori.html', [
'categories' => $categories,
'token' => Token::generate()
]);
$this->table = 'pengumuman';
} else {
throw new \Exception("Bad request", 400);
}
@ -186,34 +188,34 @@ class Posts
public function post($args = [])
{
if (isset($args['_addon'])) {
$this->table = $args['_addon'];
$table = $args['_addon'];
unset($args['_addon']);
}
foreach ($args as $value) {
if ($value == '') {
Session::flash('info', 'Semua data harus diisi.');
if ($this->table == 'pengumuman') {
if ($table) {
Redirect::to("/posts/category");
} else {
Redirect::to('/posts/entry');
} elseif ($this->table == 'kategori') {
Redirect::to('/posts/category');
}
die();
}
}
if ($this->model->entry($this->table, $args)) {
Session::flash('info', 'Data berhasil diunggah.');
if ($this->table == 'kategori') {
if (isset($table)) {
if ($this->model->entry($args, $table)) {
Session::flash('info', 'Data berhasil diunggah.');
Redirect::to('/posts/category');
} elseif ($this->table == 'pengumuman') {
}
} else {
if ($this->model->entry($args)) {
Session::flash('info', 'Data berhasil diunggah.');
Redirect::to('/');
}
}
// Return the $table back to default
$this->table = 'pengumuman';
die();
}
public function put($args = [])
@ -221,10 +223,11 @@ class Posts
if (isset($args['_addon'])) {
$table = $args['_addon'];
$this->model->update($table, ['status' => 1], $args['id']);
$this->model->update(['status' => 1], $args['id'], $table);
Session::flash('info', 'Data berhasil diaktifkan.');
Redirect::to('/posts/category');
die();
}
$args['content'] = htmlspecialchars($args['content']);
@ -258,28 +261,29 @@ class Posts
}
}
if ($this->model->update($this->table, $args, $id)) {
if ($this->model->update($args, $id)) {
Session::flash('info', 'Data berhasil diperbarui.');
Redirect::to('/');
} else {
Session::flash('info', 'Terjadi kesalahan. Silahkan coba lagi dalam beberapa saat.');
Redirect::to("./$id");
}
die();
}
public function delete($args = [])
{
if (isset($args['_addon'])) {
$this->table = $args['_addon'];
$table = $args['_addon'];
unset($args['_addon']);
}
$id = $args['id'];
if ($this->table == 'kategori') {
$delete = $this->model->delete($this->table, $id, 0);
if ($table) {
$delete = $this->model->delete($id, 0, $table);
} else {
$delete = $this->model->delete($this->table, $id);
$delete = $this->model->delete($id);
}
if ($delete == true) {
@ -287,15 +291,14 @@ class Posts
} else {
$info = 'Terjadi kesalahan. Silahkan coba lagi dalam beberapa saat.';
}
// Return the $table back to default
$this->table = 'pengumuman';
Session::flash('info', $info);
if ($this->table = 'kategori') {
Redirect::to('/posts/category');
} elseif ($this->table = 'pengumuman') {
if ($table) {
Redirect::to("/posts/category");
} else {
Redirect::to('/');
}
die();
}
}

View File

@ -6,7 +6,6 @@ class Access extends \Core\Model
public function __construct()
{
$this->createTable(
'user',
[
'id int(3) NOT NULL AUTO_INCREMENT',
'username varchar(25) NOT NULL',
@ -21,4 +20,212 @@ class Access extends \Core\Model
]
);
}
protected function createTable($fields, $table = 'users') {
try {
if ($fields == []) {
return false;
}
$sql = "CREATE TABLE IF NOT EXISTS {$table} (".implode(',', $fields).") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
$db = static::connectDB();
$query = $db->prepare($sql);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
protected function dropTable($table = 'users') {
try {
$sql = "DROP TABLE IF EXISTS {$table}";
$db = static::connectDB();
$query = $db->prepare($sql);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
public function showAll($conditions = [], $table = 'users')
{
try {
$db = static::connectDB();
$sql = "SELECT * FROM {$table}";
if ($conditions) {
$sql .= " WHERE";
foreach ($conditions as $condition) {
$keys[] = $condition[0];
$operators[] = $condition[1];
$values[] = $condition[2];
}
$x = 0;
foreach ($keys as $key) {
$sql .= " $key $operators[$x] ?";
$x++;
if ($x < count($keys)) {
$sql .= " AND";
}
}
}
$query = $db->prepare($sql);
if (count($conditions)) {
$x = 1;
foreach ($values as $value) {
$query->bindValue($x, $value);
$x++;
}
}
$query->execute();
if ($query->rowCount() == 1) {
$result = $query->fetch(\PDO::FETCH_ASSOC);
} elseif ($query->rowCount() > 1) {
$result = $query->fetchAll(\PDO::FETCH_ASSOC);
} else {
return false;
}
return $result;
} catch (PDOException $e) {
throw new \Exception($e->getMessage, 444);
}
}
public function entry($args, $table = 'users')
{
if (count($args)) {
$keys = '`'.implode('`, `', array_keys($args)).'`';
$values = '';
// This is if want to insert multiple rows
foreach ($args as $key => $val) {
if (preg_match('/,/', $val)) {
$val = explode(',', $val);
$args[$key] = $val;
}
}
$x = 1;
foreach ($args as $field) {
// Setting the query for multiple rows
if (is_array($field)) {
foreach ($field as $fields) {
$values .= '(?)';
if ($x < count($field)) {
$values .= ', ';
}
$x++;
}
} else {
if ($x === 1) {
$values .= '(';
}
$values .= '?';
if ($x < count($args)) {
$values .= ', ';
} else {
$values .= ')';
}
$x++;
}
}
try {
$sql = "INSERT INTO {$table} ({$keys}) VALUES {$values}";
$db = static::connectDB();
$query = $db->prepare($sql);
$x = 1;
foreach ($args as $value) {
if (is_array($value)) {
foreach ($value as $vals) {
$query->bindValue($x, $vals);
$x++;
}
} else {
$query->bindValue($x, $value);
$x++;
}
}
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
return false;
}
public function update($args, $id, $table = 'users')
{
if (count($args)) {
$keys = array_keys($args);
$fields = [];
foreach ($keys as $key) {
$fields[] = $key.' = ?';
}
if (count($fields) > 1) {
$fields = implode(', ', $fields);
} else {
$fields = implode('', $fields);
}
try {
$db = static::connectDB();
$result = $this->showAll([
['id', '=', $id]
]);
$sql = "UPDATE {$table} SET {$fields} WHERE id = ?";
$query = $db->prepare($sql);
$x = 1;
foreach ($args as $value) {
$query->bindValue($x, $value);
$x++;
}
$query->bindValue($x, $id);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
return false;
}
public function delete($id, $status, $table = 'users')
{
try {
$db = static::connectDB();
$sql = "UPDATE {$table} SET status = ? WHERE id = ?";
$query = $db->prepare($sql);
$query->bindValue(1, $status);
$query->bindValue(2, $id);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
}

View File

@ -7,7 +7,6 @@ class Post extends \Core\Model
{
// Create table for posts
$this->createTable(
'pengumuman',
[
'id int(3) NOT NULL AUTO_INCREMENT',
'category int(3) NOT NULL',
@ -25,13 +24,221 @@ class Post extends \Core\Model
// Create table for categories
$this->createTable(
'kategori',
[
'id int(3) NOT NULL AUTO_INCREMENT',
'category varchar(20) NOT NULL',
'status tinyint(1) NOT NULL DEFAULT 1',
'PRIMARY KEY (id)'
]
],
'kategori'
);
}
protected function createTable($fields, $table = 'pengumuman') {
try {
if (empty($fields)) {
return false;
}
$sql = "CREATE TABLE IF NOT EXISTS {$table} (".implode(',', $fields).") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
$db = static::connectDB();
$query = $db->prepare($sql);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
protected function dropTable($table = 'pengumuman') {
try {
$sql = "DROP TABLE IF EXISTS {$table}";
$db = static::connectDB();
$query = $db->prepare($sql);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
public function showAll($conditions = [], $table = 'pengumuman')
{
try {
$db = static::connectDB();
$sql = "SELECT * FROM {$table}";
if ($conditions) {
$sql .= " WHERE";
foreach ($conditions as $condition) {
$keys[] = $condition[0];
$operators[] = $condition[1];
$values[] = $condition[2];
}
$x = 0;
foreach ($keys as $key) {
$sql .= " $key $operators[$x] ?";
$x++;
if ($x < count($keys)) {
$sql .= " AND";
}
}
}
$query = $db->prepare($sql);
if (count($conditions)) {
$x = 1;
foreach ($values as $value) {
$query->bindValue($x, $value);
$x++;
}
}
$query->execute();
if ($query->rowCount() == 1) {
$result = $query->fetch(\PDO::FETCH_ASSOC);
} elseif ($query->rowCount() > 1) {
$result = $query->fetchAll(\PDO::FETCH_ASSOC);
} else {
return false;
}
return $result;
} catch (PDOException $e) {
throw new \Exception($e->getMessage, 444);
}
}
public function entry($args, $table = 'pengumuman')
{
if (count($args)) {
$keys = '`'.implode('`, `', array_keys($args)).'`';
$values = '';
// This is if want to insert multiple rows
foreach ($args as $key => $val) {
if (preg_match('/,/', $val)) {
$val = explode(',', $val);
$args[$key] = $val;
}
}
$x = 1;
foreach ($args as $field) {
// Setting the query for multiple rows
if (is_array($field)) {
foreach ($field as $fields) {
$values .= '(?)';
if ($x < count($field)) {
$values .= ', ';
}
$x++;
}
} else {
if ($x === 1) {
$values .= '(';
}
$values .= '?';
if ($x < count($args)) {
$values .= ', ';
} else {
$values .= ')';
}
$x++;
}
}
try {
$sql = "INSERT INTO {$table} ({$keys}) VALUES {$values}";
$db = static::connectDB();
$query = $db->prepare($sql);
$x = 1;
foreach ($args as $value) {
if (is_array($value)) {
foreach ($value as $vals) {
$query->bindValue($x, $vals);
$x++;
}
} else {
$query->bindValue($x, $value);
$x++;
}
}
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
return false;
}
public function update($args, $id, $table = 'pengumuman')
{
if (count($args)) {
$keys = array_keys($args);
$fields = [];
foreach ($keys as $key) {
$fields[] = $key.' = ?';
}
if (count($fields) > 1) {
$fields = implode(', ', $fields);
} else {
$fields = implode('', $fields);
}
try {
$db = static::connectDB();
$result = $this->showAll([
['id', '=', $id]
]);
$sql = "UPDATE {$table} SET {$fields} WHERE id = ?";
$query = $db->prepare($sql);
$x = 1;
foreach ($args as $value) {
$query->bindValue($x, $value);
$x++;
}
$query->bindValue($x, $id);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
return false;
}
public function delete($id, $status, $table = 'pengumuman')
{
try {
$db = static::connectDB();
$sql = "UPDATE {$table} SET status = ? WHERE id = ?";
$query = $db->prepare($sql);
$query->bindValue(1, $status);
$query->bindValue(2, $id);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
}

View File

@ -22,222 +22,11 @@ abstract class Model
}
}
public function createTable($table, $fields = [])
{
try {
$sql = "CREATE TABLE IF NOT EXISTS {$table} (".implode(',', $fields).") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
abstract protected function createTable($fields);
abstract protected function dropTable();
$db = static::connectDB();
$query = $db->prepare($sql);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
public function dropTable($table)
{
try {
if (is_array($table)) {
if (count($table)) {
$table = implode(', ', $table);
}
}
$sql = "DROP TABLE IF EXISTS {$table}";
$db = static::connectDB();
$query = $db->prepare($sql);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
public function showAll($table, $conditions = [])
{
try {
if ($table) {
$db = static::connectDB();
$sql = "SELECT * FROM $table";
if ($conditions) {
$sql .= " WHERE";
foreach ($conditions as $condition) {
$keys[] = $condition[0];
$operators[] = $condition[1];
$values[] = $condition[2];
}
$x = 1;
$i = 0;
foreach ($keys as $key) {
$sql .= " $key $operators[$i] ?";
$i++;
$x++;
if ($x <= count($keys)) {
$sql .= " AND";
}
}
}
$query = $db->prepare($sql);
if ($conditions) {
$x = 1;
foreach ($values as $value) {
$query->bindValue($x, $value);
$x++;
}
}
$query->execute();
if ($query->rowCount() == 1) {
$result = $query->fetch(\PDO::FETCH_ASSOC);
} elseif ($query->rowCount() > 1) {
$result = $query->fetchAll(\PDO::FETCH_ASSOC);
} else {
return false;
}
return $result;
}
return false;
} catch (PDOException $e) {
throw new \Exception($e->getMessage, 444);
}
}
public function entry($table, $args, $values = '')
{
if (count($args)) {
$keys = '`'.implode('`, `', array_keys($args)).'`';
// This is if want to insert multiple rows
foreach ($args as $key => $val) {
if (preg_match('/,/', $val)) {
$val = explode(',', $val);
$args[$key] = $val;
}
}
$x = 1;
foreach ($args as $field) {
// Setting the query for multiple rows
if (is_array($field)) {
foreach ($field as $fields) {
$values .= '(?)';
if ($x < count($field)) {
$values .= ', ';
}
$x++;
}
} else {
if ($x === 1) {
$values .= '(';
}
$values .= '?';
if ($x < count($args)) {
$values .= ', ';
} else {
$values .= ')';
}
$x++;
}
}
try {
$sql = "INSERT INTO {$table} ({$keys}) VALUES {$values}";
$db = static::connectDB();
$query = $db->prepare($sql);
$x = 1;
foreach ($args as $value) {
if (is_array($value)) {
foreach ($value as $vals) {
$query->bindValue($x, $vals);
$x++;
}
} else {
$query->bindValue($x, $value);
$x++;
}
}
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
}
public function update($table, $args, $id)
{
if (count($args)) {
$keys = array_keys($args);
$fields = [];
foreach ($keys as $key) {
$fields[] = $key.' = ?';
}
if (count($fields) > 1) {
$fields = implode(', ', $fields);
} else {
$fields = implode('', $fields);
}
try {
$db = static::connectDB();
$result = $this->showAll($table, [
['id', '=', $id]
]);
$sql = "UPDATE {$table} SET {$fields} WHERE id = ?";
$query = $db->prepare($sql);
$x = 1;
foreach ($args as $value) {
$query->bindValue($x, $value);
$x++;
}
$query->bindValue($x, $id);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
}
public function delete($table, $id, $force = '')
{
try {
$db = static::connectDB();
$sql = "UPDATE {$table} SET status = ? WHERE id = ?";
$query = $db->prepare($sql);
if (is_int($force)) {
$query->bindValue(1, $force);
} else {
$query->bindValue(1, 3);
}
$query->bindValue(2, $id);
$query->execute();
return true;
} catch (PDOException $e) {
throw new \Exception($e->getMessage(), 444);
}
}
abstract public function showAll($conditions = []);
abstract public function entry($args);
abstract public function update($args, $id);
abstract public function delete($id, $status);
}