lepisi-pengumuman/App/Models/Post.php

129 lines
3.4 KiB
PHP

<?php
namespace App\Models;
class Post extends \Core\Model
{
public function __construct()
{
// Create table for posts
$this->createTable(
'pengumuman',
[
'id int(3) NOT NULL AUTO_INCREMENT',
'category int(3) NOT NULL',
'created_at date NOT NULL DEFAULT CURRENT_TIMESTAMP',
'valid_at date NOT NULL DEFAULT CURRENT_TIMESTAMP',
'expired_at date NOT NULL',
'creator int(3) NOT NULL',
'edited_at date',
'editor date',
'content varchar(255) NOT NULL',
'status tinyint NOT NULL DEFAULT 1',
'PRIMARY KEY (id)'
]
);
// Create table for categories
$this->createTable(
'kategori',
[
'id int(3) NOT NULL AUTO_INCREMENT',
'category varchar(20) NOT NULL',
'status tinyint NOT NULL DEFAULT 1',
'PRIMARY KEY (id)'
]
);
}
public function showAll($conditions = [])
{
try {
$db = static::connectDB();
$sql = "SELECT * FROM pengumuman";
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++;
}
}
if ($query->execute()) {
if ($query->rowCount() != 0) {
$result = $query->fetchAll(\PDO::FETCH_ASSOC);
return $result;
}
}
return false;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function showSingle($id)
{
try {
$db = static::connectDB();
$sql = "SELECT * FROM pengumuman WHERE id = ?";
$query = $db->prepare($sql);
if ($query->execute([$id])) {
if ($query->rowCount() === 1) {
$result = $query->fetch(\PDO::FETCH_ASSOC);
return $result;
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function showCategories()
{
try {
$db = static::connectDB();
$sql = "SELECT * FROM kategori WHERE status = 1";
$query = $db->prepare($sql);
if ($query->execute()) {
if ($query->rowCount() > 1) {
$results = $query->fetchAll(\PDO::FETCH_ASSOC);
return $results;
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}