Home >Backend Development >PHP Tutorial >How to implement an online voting system in PHP?

How to implement an online voting system in PHP?

PHPz
PHPzOriginal
2023-05-12 08:36:361368browse

In modern society, voting has become a very important behavior. It is closely related to values ​​such as democracy, justice, and fairness. Its importance needs no introduction. For many websites and companies, in order to collect the opinions and decisions of user groups, it has become increasingly necessary to implement online voting systems. In this article, we will take an in-depth look at how to implement an efficient, scalable, and secure online voting system in PHP.

  1. Database Design

When implementing an online voting system, data storage is a crucial step. In order to ensure data security and scalability, we can use MySQL or other relational databases. In the database design, we need to create at least two tables: user table and voting table.

The user table includes user ID, user name, password, email address and other information. We can also add some other fields, such as user type, user permissions, etc. The voting table includes voting ID, voting topic, voting options, voting results and other information. In order to implement online voting, we need to create a unique voting ID for each voting transaction.

The following is a simple MySQL code example:

CREATE TABLE users (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(30) NOT NULL,
  password VARCHAR(30) NOT NULL,
  email VARCHAR(50),
  type ENUM('user', 'admin') NOT NULL
);

CREATE TABLE polls (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT(6) UNSIGNED,
  question VARCHAR(200) NOT NULL,
  UNIQUE (id)
);

CREATE TABLE options (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  poll_id INT(6) UNSIGNED,
  name VARCHAR(50) NOT NULL,
  votes INT(6) UNSIGNED DEFAULT 0,
  UNIQUE (id)
);
  1. User authentication

User authentication is crucial when implementing an online voting system step. We need to ensure that only registered users can create new poll topics and vote. In basic PHP applications, we usually use SESSION sessions to control the user's login status so that they can remember their identity when they browse the website. The following is a simple user login page and basic PHPSESSION code example:

<?php
session_start();

if($_SERVER["REQUEST_METHOD"] == "POST") {
  // 用户提交表单数据,进行身份验证
  $username = $_POST['username'];
  $password = $_POST['password'];

  // 在数据库中查找用户名和密码
  $sql = "SELECT id, type FROM users WHERE username = '$username' and password = '$password'";
  $result = mysqli_query($db,$sql);
  $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
  
  // 如果用户存在,创建SESSION变量并跳转到投票主题页面
  if(mysqli_num_rows($result) == 1) {
    $_SESSION['login_user'] = $username;
    $_SESSION['login_id'] = $row['id'];
    $_SESSION['login_type'] = $row['type'];
    header("location: polls.php");
  }
  // 如果用户不存在或者密码错误,则显示错误消息
  else {
    $error = "用户名或密码错误!";
  }
}

?>

<!DOCTYPE html>
<html>
<head>
  <title>用户登录</title>
</head>
<body>
  <form method="post">
    <label>用户名:</label><input type="text" name="username"><br>
    <label>密码:</label><input type="password" name="password"><br>
    <input type="submit" value="登录">
  </form>
  <?php
  if(isset($error)) {
    echo "<div>$error</div>";
  }
  ?>
</body>
</html>
  1. Voting topic page

The voting topic page is the core component of the online voting system. In this page we can display all currently existing polling topics and allow users to create new polling topics. When users click on the voting topic, we will jump them to the voting page to make it easier for them to vote. Here is an example of PHP code for a simple voting theme page:

<?php
session_start();

// 检查用户是否已经登录
if(!isset($_SESSION['login_user'])) {
  header("location: login.php");
}

// 处理创建新投票请求
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['question'])) {
  // 添加一个新的投票主题
  $question = $_POST['question'];
  $user_id = $_SESSION['login_id'];
  $sql = "INSERT INTO polls (question, user_id) VALUES ('$question', $user_id)";
  mysqli_query($db,$sql);
}

// 从数据库中检索所有的投票主题
$sql = "SELECT * FROM polls ORDER BY id DESC";
$result = mysqli_query($db,$sql);

// 渲染HTML模板,显示所有的投票主题
?>
<!DOCTYPE html>
<html>
<head>
  <title>投票主题</title>
</head>
<body>
  <h2>投票主题列表</h2>
  <ul>
  <?php
  while($row = mysqli_fetch_assoc($result)) {
    echo "<li><a href='vote.php?id={$row['id']}'>{$row['question']}</a></li>";
  }
  ?>
  </ul>
  <?php
  // 如果用户是管理员,则显示一个表单以添加新的投票主题
  if($_SESSION['login_type'] == 'admin') {
    echo "<form method='post'>
      <label>新主题:</label><input type='text' name='question'>
      <input type='submit' value='添加'>
      </form>";
  }
  ?>
  <a href='logout.php'>注销</a>
</body>
</html>
  1. Voting Page

The voting page is the key part that allows users to vote. In this page we need to display voting options and allow users to vote for their favorite option. At the same time, we need to display the current vote number and percentage for user reference.

The following is an example of PHP code for a simple voting page:

<?php
session_start();

// 检查用户是否已经登录
if(!isset($_SESSION['login_user'])) {
  header("location: login.php");
}

// 处理投票请求
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['option'])) {
  $poll_id = intval($_GET['id']);
  $option_id = intval($_POST['option']);
  $user_id = $_SESSION['login_id'];

  // 检查用户是否已经投过票
  $sql = "SELECT id FROM votes WHERE user_id = $user_id AND poll_id = $poll_id";
  $result = mysqli_query($db,$sql);
  if(mysqli_num_rows($result) == 0) {
    // 在数据库中增加一个新的投票
    $sql = "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($user_id, $poll_id, $option_id)";
    mysqli_query($db,$sql);

    // 更新选项投票数
    $sql = "UPDATE options SET votes = votes + 1 WHERE id = $option_id";
    mysqli_query($db,$sql);
  }
}

// 获取当前投票的所有信息
$poll_id = intval($_GET['id']);
$sql = "SELECT * FROM polls WHERE id = $poll_id";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_assoc($result);

// 获取投票选项和投票结果
$sql = "SELECT options.*, COUNT(votes.id) as count FROM options LEFT JOIN votes ON votes.option_id = options.id WHERE options.poll_id = $poll_id GROUP BY options.id";
$result = mysqli_query($db,$sql);

// 渲染HTML模板以显示投票主题和选项
?>
<!DOCTYPE html>
<html>
<head>
  <title>投票 - <?php echo $row['question']; ?></title>
</head>
<body>
  <h2><?php echo $row['question']; ?></h2>
  <form method="post">
  <ul>
  <?php
  while($row = mysqli_fetch_assoc($result)) {
    echo "<li>";
    echo "<label><input type='radio' name='option' value='{$row['id']}' required>{$row['name']}</label>";
    echo "<span>{$row['count']} votes (".round($row['count']*100/$total)."%)</span>";
    echo "</li>";
  }
  ?>
  </ul>
  <input type="submit" value="投票">
  </form>
  <a href='polls.php'>返回</a>
  <?php
  // 如果用户已经投了票,则显示一条 "您已经投票了!" 的消息
  $user_id = $_SESSION['login_id'];
  $sql = "SELECT id FROM votes WHERE user_id = $user_id AND poll_id = $poll_id";
  $result = mysqli_query($db,$sql);
  if(mysqli_num_rows($result) == 1) {
    echo "<p>您已经投票了!</p>";
  }
  ?>
</body>
</html>
  1. Summary

Through the above steps, we have successfully achieved a quality An online voting system with high performance, safety, reliability and complete functions. But this is just a simple example. In actual applications, more functions and security features may need to be added, such as data verification, role access control, etc. In any case, security, scalability and user-friendliness should be the primary considerations during the design and implementation of online voting systems.

The above is the detailed content of How to implement an online voting system in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn