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; ?> Poll Application

Available Polls

query("SELECT id, question_text, created_at FROM poll_questions ORDER BY id DESC"); $allPolls = $allPollsStmt->fetchAll(PDO::FETCH_ASSOC); if ($allPolls) { foreach ($allPolls as $poll) { ?>
Question:
Created at:
View Poll

No polls available.

Poll not found.

"; } else { $options = getPollOptions($db, $pollId); $hasVoted = in_array($pollId, $_SESSION['voted_polls'], true); ?>

No options available for this poll.

"; } } else { // Show the results if user has already voted ?>

Results

Total votes:

Back to Poll List