Home > Article > Backend Development > How to implement a simple voting system using PHP
How to use PHP to implement a simple voting system
1. Introduction
With the continuous development of the Internet, voting activities on social networks and online platforms are becoming more and more popular. becoming more and more common. To meet this need, we can implement a simple voting system using the PHP programming language. This article will introduce how to write a simple voting system using PHP and provide specific code examples.
2. Overview of system requirements
Our voting system needs to meet the following requirements:
3. Data structure design
In order to implement the voting system, we need to design the following database tables:
4. Code Implementation
The key PHP code examples for implementing the voting system are listed below:
$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
?>
foreach ($subjects as $subject) {
echo $subject['title'] . '<br>'; $subject_id = $subject['id']; $sql = "SELECT * FROM vote_options WHERE subject_id = $subject_id"; $stmt = $conn->query($sql); $options = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($options as $option) { echo $option['option_name'] . ': ' . $option['votes'] . ' votes<br>'; }
}
?> ;
$sql = "SELECT COUNT(*) FROM votes WHERE option_id = $option_id AND ip_address = '$ip_address'";
$stmt = $conn->query($sql);
$count = $stmt->fetchColumn();
if ($count > 0) {
echo '您已经投过票了!';
} else {
$sql = "UPDATE vote_options SET votes = votes + 1 WHERE id = $option_id"; $conn->exec($sql); $sql = "INSERT INTO votes (option_id, ip_address) VALUES ($option_id, '$ip_address')"; $conn->exec($sql); echo '投票成功!';
}
?>
Create a voting subject:
$title = $_POST['title'];
$sql = "INSERT INTO vote_subjects (title) VALUES ('$title')";
$conn->exec($sql);
?>
Create voting options:
$ subject_id = $_POST['subject_id'];
$option_name = $_POST['option_name'];
$sql = "INSERT INTO vote_options (subject_id, option_name, votes) VALUES ($subject_id, ' $option_name', 0)";
$conn->exec($sql);
?>
Edit voting options:
$id = $_POST['id'];
$option_name = $_POST['option_name'];
$sql = "UPDATE vote_options SET option_name = '$option_name' WHERE id = $id";
$conn->exec($sql);
?>
Delete voting option:
$id = $_POST['id'];
$sql = "DELETE FROM vote_options WHERE id = $id";
$conn->exec($sql);
?>
5. Summary
The above is a code example of writing a simple voting system using PHP. We introduced how to connect to the database, query voting topics and options, vote, and implement administrator functions. Through these code examples, you can learn how to use the PHP programming language to implement a simple voting system. Of course, this is just a simple example, and actual voting systems may require more functionality and security considerations.
The above is the detailed content of How to implement a simple voting system using PHP. For more information, please follow other related articles on the PHP Chinese website!