You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML和PHP限制同一表单每日仅提交一次?

Hey there! I get that you're new to HTML/PHP and building this voting form from scratch after your previous service changed—let's walk through how to make this work, including the daily one-vote per user limit.

First, we'll need a way to track votes, so let's start with a database table to store user votes and their dates. Then we'll build the form, and finally the PHP logic to check for existing votes and record new ones.

1. Create a Database Table (MySQL Example)

You'll need a table to keep track of who voted and when. Here's a basic schema you can run in your MySQL admin tool (like phpMyAdmin):

CREATE TABLE votes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    vote_date DATE NOT NULL,
    UNIQUE KEY unique_user_per_day (username, vote_date) -- This enforces one vote per user per day at the database level
);

That UNIQUE KEY is a safety net—it stops duplicate votes for the same user on the same day even if the PHP logic has a hiccup.

2. Build the HTML Form

This is a simple form that lets users enter their username and submit their vote. Save this as vote-form.html (or embed it in a PHP file if you want to add dynamic content later):

<!DOCTYPE html>
<html>
<head>
    <title>Vote for Our Site</title>
</head>
<body>
    <h2>Help Us Grow—Cast Your Vote!</h2>
    <?php if (isset($_GET['message'])): ?>
        <p><?php echo htmlspecialchars($_GET['message']); ?></p>
    <?php endif; ?>
    <form method="POST" action="vote-handler.php">
        <label for="username">Your Username:</label>
        <input type="text" id="username" name="username" required>
        <button type="submit">Submit Vote</button>
    </form>
</body>
</html>

We added a section to show feedback messages (like success or error alerts) after submission so users know what happened.

3. PHP Vote Handling Script (vote-handler.php)

This script will handle the form submission, check if the user has already voted today, and record the vote if they haven't. Make sure to replace the database credentials with your own:

<?php
// Database configuration
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_db_username';
$password = 'your_db_password';

// Connect to database using mysqli
$conn = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Only process if form is submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get and sanitize username input
    $username = trim($_POST['username']);
    $username = htmlspecialchars($username);

    // Validate username isn't empty
    if (empty($username)) {
        header("Location: vote-form.html?message=Please enter your username.");
        exit;
    }

    // Get today's date in YYYY-MM-DD format
    $today = date('Y-m-d');

    // Check if user already voted today
    $checkStmt = $conn->prepare("SELECT id FROM votes WHERE username = ? AND vote_date = ?");
    $checkStmt->bind_param("ss", $username, $today);
    $checkStmt->execute();
    $checkStmt->store_result();

    if ($checkStmt->num_rows > 0) {
        // User already voted today
        header("Location: vote-form.html?message=You've already voted today! Come back tomorrow.");
        $checkStmt->close();
        $conn->close();
        exit;
    }

    // If no vote today, insert new vote
    $insertStmt = $conn->prepare("INSERT INTO votes (username, vote_date) VALUES (?, ?)");
    $insertStmt->bind_param("ss", $username, $today);

    if ($insertStmt->execute()) {
        header("Location: vote-form.html?message=Thank you for your vote!");
    } else {
        header("Location: vote-form.html?message=Oops, something went wrong. Please try again.");
    }

    // Clean up resources
    $checkStmt->close();
    $insertStmt->close();
    $conn->close();
} else {
    // Redirect to form if someone tries to access this script directly
    header("Location: vote-form.html");
    exit;
}
?>

4. Important Tips for Your First Project

  • Security First: We used prepared statements to prevent SQL injection—never concatenate user input directly into SQL queries! That's a critical rule to keep your database safe.
  • Input Validation: We added a basic check for empty usernames, but you could expand this (e.g., limit username length, disallow special characters) if your site has specific username rules.
  • Database Credentials: Don't leave your database username/password hardcoded in the script long-term. Store them in a separate config file outside your web root for extra safety.
  • Error Handling: The current script uses simple redirects with messages, but you could add more detailed error logging (like writing to a file) to debug issues if they pop up.

That should cover what you need to get started. As you learn more, you can expand this—like adding user authentication if you have a login system, or styling the form to match your site's design!

内容的提问来源于stack exchange,提问作者Sets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:58:57