From f9ad3f4dc05252839457579303a4e0a0f94d8b80 Mon Sep 17 00:00:00 2001 From: Thomas Vanbesien Date: Sat, 21 Mar 2026 22:55:13 +0100 Subject: Add likes, comments, email notifications, and pagination to gallery --- src/app/Models/Comment.php | 39 ++++++++++++++++++++++++++++++ src/app/Models/Like.php | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 src/app/Models/Comment.php create mode 100644 src/app/Models/Like.php (limited to 'src/app/Models') diff --git a/src/app/Models/Comment.php b/src/app/Models/Comment.php new file mode 100644 index 0000000..464cfe2 --- /dev/null +++ b/src/app/Models/Comment.php @@ -0,0 +1,39 @@ +pdo = Database::getInstance()->getPdo(); + } + + public function create(int $userId, int $postId, string $content): int + { + $stmt = $this->pdo->prepare( + 'INSERT INTO comments (user_id, post_id, content) VALUES (:user_id, :post_id, :content)' + ); + $stmt->execute(['user_id' => $userId, 'post_id' => $postId, 'content' => $content]); + return (int) $this->pdo->lastInsertId(); + } + + public function findByPostId(int $postId): array + { + $stmt = $this->pdo->prepare( + 'SELECT comments.*, users.username FROM comments + JOIN users ON comments.user_id = users.id + WHERE comments.post_id = :post_id + ORDER BY comments.created_at ASC' + ); + $stmt->execute(['post_id' => $postId]); + return $stmt->fetchAll(); + } +} diff --git a/src/app/Models/Like.php b/src/app/Models/Like.php new file mode 100644 index 0000000..dc019a0 --- /dev/null +++ b/src/app/Models/Like.php @@ -0,0 +1,59 @@ +pdo = Database::getInstance()->getPdo(); + } + + /** + * Toggle a like: insert if not yet liked, delete if already liked. + * Returns true if the post is now liked, false if unliked. + */ + public function toggle(int $userId, int $postId): bool + { + // INSERT IGNORE silently fails when the UNIQUE(user_id, post_id) constraint + // is violated, meaning the user already liked this post + $stmt = $this->pdo->prepare( + 'INSERT IGNORE INTO likes (user_id, post_id) VALUES (:user_id, :post_id)' + ); + $stmt->execute(['user_id' => $userId, 'post_id' => $postId]); + + if ($stmt->rowCount() > 0) { + return true; + } + + // Row wasn't inserted → already liked → remove the like + $stmt = $this->pdo->prepare( + 'DELETE FROM likes WHERE user_id = :user_id AND post_id = :post_id' + ); + $stmt->execute(['user_id' => $userId, 'post_id' => $postId]); + return false; + } + + public function countByPost(int $postId): int + { + $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM likes WHERE post_id = :post_id'); + $stmt->execute(['post_id' => $postId]); + return (int) $stmt->fetchColumn(); + } + + public function hasUserLiked(int $userId, int $postId): bool + { + $stmt = $this->pdo->prepare( + 'SELECT 1 FROM likes WHERE user_id = :user_id AND post_id = :post_id LIMIT 1' + ); + $stmt->execute(['user_id' => $userId, 'post_id' => $postId]); + return $stmt->fetch() !== false; + } +} -- cgit v1.2.3