diff --git a/polls/index.php b/polls/index.php new file mode 100644 index 0000000..c961bac --- /dev/null +++ b/polls/index.php @@ -0,0 +1,201 @@ +prepare("SELECT * FROM poll_questions WHERE id = :id LIMIT 1"); + $stmt->bindValue(':id', $pollId, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetch(PDO::FETCH_ASSOC); +} + +// Helper function: Fetch poll options (and their results) by poll ID +function getPollOptions($db, $pollId) { + $stmt = $db->prepare(" + SELECT + po.id AS option_id, + po.option_text, + IFNULL(pr.vote_count, 0) AS vote_count + FROM poll_options po + LEFT JOIN poll_results pr ON po.id = pr.option_id + WHERE po.question_id = :question_id + ORDER BY po.id ASC + "); + $stmt->bindValue(':question_id', $pollId, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchAll(PDO::FETCH_ASSOC); +} + +// If a vote is being cast +if (isset($_POST['vote']) && isset($_POST['option_id']) && isset($_POST['poll_id'])) { + $pollId = (int)$_POST['poll_id']; + $optionId = (int)$_POST['option_id']; + + // Ensure this user hasn't already voted on this poll in this session + if (!in_array($pollId, $_SESSION['voted_polls'], true)) { + // Update the vote count + $updateStmt = $db->prepare(" + UPDATE poll_results + SET vote_count = vote_count + 1 + WHERE question_id = :question_id + AND option_id = :option_id + "); + $updateStmt->bindValue(':question_id', $pollId, PDO::PARAM_INT); + $updateStmt->bindValue(':option_id', $optionId, PDO::PARAM_INT); + $updateStmt->execute(); + + // Mark the user as having voted + $_SESSION['voted_polls'][] = $pollId; + } + + // Redirect back to the same poll to show results + header("Location: index.php?poll_id=" . $pollId); + exit; +} + +// Check if a specific poll is requested +$pollId = isset($_GET['poll_id']) ? (int)$_GET['poll_id'] : null; +?> + + +
+ +No polls available.
+ +Total votes:
+