With the widespread use of the internet, online voting has become an essential part of various activities, surveys, and elections. This article will introduce how to build a multi-functional online voting system using PHP, allowing users to create votes, participate in others' votes, and view real-time voting results.
The system uses the following technology stack:
Users can register and log into the system to create their own votes or participate in others' votes and view the voting results.
Users can create multiple votes and set vote titles, options, and other configurations. Below is an example of the code for creating a vote:
<?php
session_start();
// Check user login status
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
exit();
}
// Handle vote submission
if(isset($_POST['submit'])){
$title = $_POST['title'];
$options = $_POST['options'];
// Validate and process the submitted data
// Record the vote in the database
}
?>
The vote creation form looks like this:
<form method="post" action="create_vote.php">
<label for="title">Vote Title</label>
<input type="text" id="title" name="title" required>
<label for="options">Options</label>
<textarea id="options" name="options" required></textarea>
<button type="submit" name="submit">Create Vote</button>
</form>
Users can view and participate in votes created by others. Below is an example of the code for participating in a vote:
<?php
session_start();
// Check user login status
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
exit();
}
// Handle vote option submission
if(isset($_POST['vote'])){
$option_id = $_POST['option'];
// Validate and process the submitted data
// Record the vote result in the database
}
?>
The vote participation form looks like this:
<form method="post" action="vote.php">
<h3>Vote Title</h3>
<input type="radio" name="option" value="1" required>Option 1<br>
<input type="radio" name="option" value="2" required>Option 2<br>
<button type="submit" name="vote">Vote</button>
</form>
Users can view the real-time results of votes, which are displayed in a chart format. Below is an example of the code for displaying the vote results:
<?php
session_start();
// Check user login status
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
exit();
}
// Fetch and process the vote result data
?>
The vote result display looks like this:
<h3>Vote Title</h3>
<p>Option 1: <?php echo $count_option1; ?></p>
<p>Option 2: <?php echo $count_option2; ?></p>
This article introduced how to implement a multi-functional online voting system using PHP, covering features such as vote creation, participation, and real-time result viewing. These features allow users to easily create and participate in voting activities and receive real-time feedback. The system can be further expanded and optimized according to actual needs to meet different scenarios.