With the advent of the internet era, people's demand for participation and expressing opinions has been growing stronger. The online voting system has become a quick and convenient way to collect group opinions and facilitate democratic decision-making.
In this article, we will introduce how to implement an online voting system based on PHP that supports diverse voting methods and provide complete code examples to help developers build their own voting platform.
Support for single-choice, multiple-choice, and rating voting methods;
Users can vote anonymously;
Administrators can create voting topics, edit options, and set voting times;
The system can calculate and display voting results in real-time.
Below is a structure example for these two tables:
CREATE TABLE vote ( id int(11) NOT NULL AUTO_INCREMENT, title varchar(255) NOT NULL, start_time datetime NOT NULL, end_time datetime NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE option ( id int(11) NOT NULL AUTO_INCREMENT, vote_id int(11) NOT NULL, content text NOT NULL, PRIMARY KEY (id), KEY vote_id (vote_id), CONSTRAINT fk_vote_id FOREIGN KEY (vote_id) REFERENCES vote (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
// Displaying the voting topic echo "<h2>" . $vote['title'] . "</h2>"; // Option selection foreach ($options as $option) { echo "<input type='" . $vote['type'] . "' name='option' value='" . $option['id'] . "'>" . $option['content'] . "<br/>"; } // Submit button echo "<input type='submit' value='Submit Vote'>";
// Submit vote if ($_SERVER['REQUEST_METHOD'] == 'POST') { $selectedOption = $_POST['option']; // Handle according to option type if ($vote['type'] == 'radio') { // Single-choice vote $voteCount = 1; } elseif ($vote['type'] == 'checkbox') { // Multiple-choice vote $voteCount = count($selectedOption); } elseif ($vote['type'] == 'rating') { // Rating vote $totalRating = $_POST['total_rating']; $voteCount = 1; } // Update voting statistics foreach ($selectedOption as $optionId) { // Perform update operation: UPDATE option SET count = count + 1 WHERE id = $optionId } }
// Query voting results $options = $db->query("SELECT * FROM option WHERE vote_id = ".$vote['id'])->fetchAll(); foreach ($options as $option) { $votePercentage = ($option['count'] / $voteCount) * 100; echo $option['content'] . ": " . $votePercentage . "%<br/>"; }