Home Backend Development PHP Tutorial How to develop a simple voting system using PHP

How to develop a simple voting system using PHP

Sep 20, 2023 pm 04:07 PM
php voting system

How to develop a simple voting system using PHP

How to use PHP to develop a simple voting system, specific code examples are required

Introduction:
With the development of the Internet, the application of voting systems has become increasingly popular, regardless of Whether for market research, elections or event voting, an easy-to-use and efficient voting system is essential. As a popular programming language, PHP can help us quickly develop a simple and fully functional voting system. This article will introduce how to develop a simple voting system using PHP and provide specific code examples.

1. System functional requirements analysis:
Before we start writing code, we need to clarify the system requirements and functions. A basic voting system should have the following functions:

  1. User registration and login functions.
  2. Create poll topics and options.
  3. Users can browse and participate in voting.
  4. Display voting results.

2. Database design:
In order to save user information, voting topics and options, and voting results, we need to design database tables. The following is a simple database design example:

  1. Users table (users):

    • id: user ID, integer type, primary key
    • username: username, string type
    • password: password, string type
    • created_at: creation time, date and time type
  2. Voting topic table (polls):

    • id: voting topic ID, integer type, primary key
    • title: voting topic title, string type
    • created_by: created User ID, integer type (associated with the user table)
    • created_at: creation time, datetime type
  3. Voting options table (options):

    • id: option ID, integer type, primary key
    • poll_id: voting topic ID, integer type (associated with the voting topic table)
    • option_text: option text, string type
  4. Voting result table (votes):

    • id: voting result ID, integer type, primary key
    • poll_id: vote Topic ID, integer type (associated with the voting topic table)
    • option_id: option ID, integer type (associated with the voting option table)
    • user_id: user ID, integer type (associated with the user table) )

3. System development steps:

  1. Create the database and connect:
    First, we need to create a database named "voting_system" database and connect to the database:

    $conn = mysqli_connect("localhost", "root", "", "voting_system");
    if (!$conn) {
        die("数据库连接失败:" . mysqli_connect_error());
    }
    Copy after login
  2. User registration and login functions:
    Users need to be able to register and log in to the system. Here is a simple code example:

    a. User registration:

    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    $sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashed_password')";
    
    if (mysqli_query($conn, $sql)) {
        echo "注册成功!";
    } else {
        echo "注册失败:" . mysqli_error($conn);
    }
    Copy after login

    b. User login:

    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $sql = "SELECT * FROM users WHERE username='$username'";
    $result = mysqli_query($conn, $sql);
    
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        if (password_verify($password, $row['password'])) {
            echo "登录成功!";
        } else {
            echo "密码错误!";
        }
    } else {
        echo "用户不存在!";
    }
    Copy after login
  3. Create polling topics and options:
    Creating voting topics and options requires users to be logged in and have corresponding permissions. The following is a simple code example:

    a. Create a voting topic:

    $title = $_POST['title'];
    $created_by = $_SESSION['user_id'];
    
    $sql = "INSERT INTO polls (title, created_by) VALUES ('$title', '$created_by')";
    
    if (mysqli_query($conn, $sql)) {
        echo "投票主题创建成功!";
    } else {
        echo "投票主题创建失败:" . mysqli_error($conn);
    }
    Copy after login

    b. Create a voting option:

    $poll_id = $_POST['poll_id'];
    $option_text = $_POST['option_text'];
    
    $sql = "INSERT INTO options (poll_id, option_text) VALUES ('$poll_id', '$option_text')";
    
    if (mysqli_query($conn, $sql)) {
        echo "投票选项创建成功!";
    } else {
        echo "投票选项创建失败:" . mysqli_error($conn);
    }
    Copy after login
  4. User participation in voting:
    Users need to browse the voting topic and select the voting option to vote. Here is a simple code example:

    a. Display voting topics and options:

    $sql = "SELECT * FROM polls";
    $result = mysqli_query($conn, $sql);
    
    while ($row = mysqli_fetch_assoc($result)) {
        echo "投票主题:" . $row['title'] . "<br>";
    
        $poll_id = $row['id'];
        $sql_options = "SELECT * FROM options WHERE poll_id='$poll_id'";
        $result_options = mysqli_query($conn, $sql_options);
    
        while ($row_option = mysqli_fetch_assoc($result_options)) {
            echo "<input type='checkbox' name='option_ids[]' value='" . $row_option['id'] . "'>" . $row_option['option_text'] . "<br>";
        }
    
        echo "<hr>";
    }
    Copy after login

    b. Handle user votes:

    $option_ids = $_POST['option_ids'];
    
    foreach ($option_ids as $option_id) {
        $sql = "INSERT INTO votes (poll_id, option_id, user_id) VALUES ('$poll_id', '$option_id', '$user_id')";
    
        if (mysqli_query($conn, $sql)) {
            echo "投票成功!";
        } else {
            echo "投票失败:" . mysqli_error($conn);
        }
    }
    Copy after login
  5. Display voting results :
    The voting results can be achieved by counting the number of votes for each option. The following is a simple code example:

    a. Statistical voting results:

    $poll_id = $_GET['poll_id'];
    
    $sql = "SELECT option_id, COUNT(*) AS vote_count FROM votes WHERE poll_id='$poll_id' GROUP BY option_id";
    $result = mysqli_query($conn, $sql);
    
    while ($row = mysqli_fetch_assoc($result)) {
        $option_id = $row['option_id'];
        $vote_count = $row['vote_count'];
    
        $sql_option = "SELECT option_text FROM options WHERE id='$option_id'";
        $result_option = mysqli_query($conn, $sql_option);
        $row_option = mysqli_fetch_assoc($result_option);
    
        echo $row_option['option_text'] . ": " . $vote_count . " 票<br>";
    }
    Copy after login

Conclusion:
This article introduces how to use PHP to develop a simple voting system, and provides specific code examples. Through the above steps, we can implement basic voting system functions such as user registration and login, creating voting topics and options, user participation in voting, and displaying voting results. According to actual needs, we can also carry out further optimization and expansion. Hope this article helps you!

The above is the detailed content of How to develop a simple voting system using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles