Home >Backend Development >PHP Tutorial >Build a customizable PHP online voting platform

Build a customizable PHP online voting platform

王林
王林Original
2023-08-08 09:25:01852browse

Build a customizable PHP online voting platform

Build a customizable PHP online voting platform

With the popularity of the Internet and the continuous development of technology, online voting has become a common way to collect public opinions and decisions. Building a customizable PHP online voting platform will provide users with a flexible, efficient and secure voting environment. This article will introduce how to use PHP to write a simple online voting platform and provide code examples.

First, we need to create a database to store voting-related data. We can use MySQL as backend database. Create a database named "voting", and then create two tables in it, "polls" and "votes".

CREATE DATABASE voting;

CREATE TABLE polls (
    id INT(11) NOT NULL AUTO_INCREMENT,
    question VARCHAR(255) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE votes (
    id INT(11) NOT NULL AUTO_INCREMENT,
    poll_id INT(11) NOT NULL,
    option_id INT(11) NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (poll_id) REFERENCES polls(id)
);

Next, we need to create a voting page that displays voting questions and options and records the user's votes. Create a file called "index.php" and add the following code:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "voting";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 获取投票问题和选项
$sql = "SELECT id, question FROM polls";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // 输出每个投票问题和选项
    while($row = $result->fetch_assoc()) {
        echo "<h2>".$row['question']."</h2>";

        $optionsSql = "SELECT id, option_name FROM options WHERE poll_id=".$row['id'];
        $optionsResult = $conn->query($optionsSql);

        if ($optionsResult->num_rows > 0) {
            // 输出每个选项的投票按钮
            while($optionRow = $optionsResult->fetch_assoc()) {
                echo '<input type="radio" name="poll'.$row['id'].'" value="'.$optionRow['id'].'"> '.$optionRow['option_name'].'<br>';
            }
        }
    }
    echo '<input type="submit" value="提交投票">';
} else {
    echo "暂无投票问题";
}

$conn->close();
?>

The above code will get the voting questions and related options from the database and display them on the page. Each option generates a radio button for the user to select. After the user selects an option, they can click the "Submit Vote" button to submit their vote.

Next, we need to process the user's votes and log them into the database. Modify the "index.php" file and add the following code:

<?php
// ...

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $pollId = $_POST['pollId'];
    $optionId = $_POST['optionId'];

    $sql = "INSERT INTO votes (poll_id, option_id) VALUES ('$pollId', '$optionId')";

    if ($conn->query($sql) === TRUE) {
        echo "投票成功";
    } else {
        echo "投票失败";
    }
}

$conn->close();
?>

The above code will process the POST request of the "Submit Voting" button and insert the voting record into the "votes" table.

In addition to the voting function, we can also add other functions to improve the customization of the voting platform. For example, adding a backend management page allows you to dynamically create voting questions and options, and view voting results. We can create a file called "admin.php" and add the following code to it:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "voting";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 查询所有投票问题
$sql = "SELECT * FROM polls";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // 输出每个投票问题和选项
    while($row = $result->fetch_assoc()) {
        echo "<h2>".$row['question']."</h2>";

        $optionsSql = "SELECT * FROM options WHERE poll_id=".$row['id'];
        $optionsResult = $conn->query($optionsSql);

        if ($optionsResult->num_rows > 0) {
            // 输出每个选项和对应的投票数
            while($optionRow = $optionsResult->fetch_assoc()) {
                $voteCountSql = "SELECT COUNT(*) AS count FROM votes WHERE poll_id=".$row['id']." AND option_id=".$optionRow['id'];
                $voteCountResult = $conn->query($voteCountSql);
                $voteCount = $voteCountResult->fetch_assoc()['count'];

                echo $optionRow['option_name'].": ".$voteCount."<br>";
            }
        }
    }
} else {
    echo "暂无投票问题";
}

$conn->close();
?>

The above code will get all the voting questions from the database and display each option and its corresponding number of votes .

The above is the implementation of a simple customizable PHP online voting platform. By using simple code examples written in PHP, we can implement functions such as voting display, recording and statistics. You can further customize and expand this platform according to your own needs, such as adding functions such as user login, voting deadline, and chart display of voting results to meet voting needs in different scenarios.

The above is the detailed content of Build a customizable PHP online voting platform. 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