aboutsummaryrefslogtreecommitdiffstats
path: root/src/app/Models
diff options
context:
space:
mode:
Diffstat (limited to 'src/app/Models')
-rw-r--r--src/app/Models/Post.php71
1 files changed, 71 insertions, 0 deletions
diff --git a/src/app/Models/Post.php b/src/app/Models/Post.php
new file mode 100644
index 0000000..66c8c18
--- /dev/null
+++ b/src/app/Models/Post.php
@@ -0,0 +1,71 @@
+<?php
+
+declare(strict_types=1);
+// Post model: database operations for the posts table.
+
+namespace App\Models;
+
+use App\Database;
+
+class Post
+{
+ private \PDO $pdo;
+
+ public function __construct()
+ {
+ $this->pdo = Database::getInstance()->getPdo();
+ }
+
+ public function create(int $userId, string $imagePath): int
+ {
+ $stmt = $this->pdo->prepare(
+ 'INSERT INTO posts (user_id, image_path) VALUES (:user_id, :image_path)'
+ );
+ $stmt->execute(['user_id' => $userId, 'image_path' => $imagePath]);
+ return (int) $this->pdo->lastInsertId();
+ }
+
+ public function findById(int $id): ?array
+ {
+ $stmt = $this->pdo->prepare('SELECT * FROM posts WHERE id = :id');
+ $stmt->execute(['id' => $id]);
+ $row = $stmt->fetch();
+ return $row ?: null;
+ }
+
+ public function findByUserId(int $userId): array
+ {
+ $stmt = $this->pdo->prepare(
+ 'SELECT * FROM posts WHERE user_id = :user_id ORDER BY created_at DESC'
+ );
+ $stmt->execute(['user_id' => $userId]);
+ return $stmt->fetchAll();
+ }
+
+ public function findAllPaginated(int $limit, int $offset): array
+ {
+ $stmt = $this->pdo->prepare(
+ 'SELECT posts.*, users.username FROM posts
+ JOIN users ON posts.user_id = users.id
+ ORDER BY posts.created_at DESC
+ LIMIT :limit OFFSET :offset'
+ );
+ // PDO needs explicit int binding for LIMIT/OFFSET
+ $stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
+ $stmt->bindValue('offset', $offset, \PDO::PARAM_INT);
+ $stmt->execute();
+ return $stmt->fetchAll();
+ }
+
+ public function countAll(): int
+ {
+ $stmt = $this->pdo->query('SELECT COUNT(*) FROM posts');
+ return (int) $stmt->fetchColumn();
+ }
+
+ public function delete(int $id): void
+ {
+ $stmt = $this->pdo->prepare('DELETE FROM posts WHERE id = :id');
+ $stmt->execute(['id' => $id]);
+ }
+}