Home  >  Article  >  Backend Development  >  Design principles and practice of PHP voting system

Design principles and practice of PHP voting system

WBOY
WBOYOriginal
2023-08-09 15:17:061552browse

Design principles and practice of PHP voting system

Design principles and practices of PHP voting system

Abstract: This article will focus on the design principles and practices of PHP voting systems. It describes the requirements analysis, database design, user authentication and authorization, front-end and back-end interaction of the voting system, etc. At the same time, the article also contains relevant PHP code examples, aiming to help readers better learn and understand the development of voting systems.

1. Requirements Analysis
Before designing the voting system, we need to clarify the system requirements. A basic voting system usually includes functions such as creating votes, publishing votes, participating in votes, and counting voting results. In this article, we will explain a simple single-choice voting system as an example.

2. Database design
In the voting system, we need to design a database to store voting-related data. Normally, we need to create the following data tables:

  • User table (user): used to store user information, such as user name, password, etc.
  • Voting table (vote): used to store voting information, such as voting topic, creation time, etc.
  • Option table (option): used to store voting option information, such as option content, belonging votes, etc.
  • Record table (record): used to store user voting records, such as user ID, voting ID, etc.

The following is the code of the database design example:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `vote` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `option` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(255) NOT NULL,
  `vote_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`vote_id`) REFERENCES `vote`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `record` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `vote_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`vote_id`) REFERENCES `vote`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3. User authentication and authorization
In the voting system, user authentication and authorization are a very important part. We need to ensure that only logged in users can vote, and that each user can only vote once per poll. The following is a sample code for user authentication and authorization:

// 登录验证
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}

// 投票操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = $_SESSION['user']['id'];
    $voteId = $_POST['voteId'];
    $optionId = $_POST['optionId'];

    // 检查是否已经投过票
    $record = $db->query("SELECT * FROM record WHERE user_id = $userId AND vote_id = $voteId")->fetch(PDO::FETCH_ASSOC);
    if (!$record) {
        // 插入投票记录
        $db->query("INSERT INTO record (user_id, vote_id) VALUES ($userId, $voteId)");
        // 更新选项的票数
        $db->query("UPDATE `option` SET count = count + 1 WHERE id = $optionId");
        echo '投票成功!';
    } else {
        echo '您已经投过票了!';
    }
}

4. Front-end and back-end interaction
In the voting system, the interaction between the front and back ends is inevitable. Usually we use Ajax to implement refresh-free voting operations and use JSON format to transmit data. The following is a sample code for front-end and back-end interaction:

// 前端代码
$('.vote-btn').click(function() {
    var voteId = $(this).data('vote-id');
    var optionId = $(this).data('option-id');
    $.ajax({
        url: 'vote.php',
        type: 'POST',
        dataType: 'json',
        data: {voteId: voteId, optionId: optionId},
        success: function(data) {
            alert(data.message);
            // 刷新页面
            location.reload();
        }
    });
});

// 后端代码(vote.php)
// 处理投票逻辑
// ...
$response = ['message' => '投票成功!'];
echo json_encode($response);

Summary: This article introduces the design principles and practices of the PHP voting system, including requirements analysis, database design, user authentication and authorization, and front-end and back-end interaction. By explaining the corresponding code examples, readers can better learn and understand the development process of the voting system. I hope this article can provide readers with some reference and help.

The above is the detailed content of Design principles and practice of PHP voting system. 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