Before developing a lottery feature, you need to create a MySQL database to store prize information, participant data, and other related information. You can use the following SQL commands to create the database and tables:
CREATE DATABASE lottery_db;
USE lottery_db;
CREATE TABLE prizes (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE participants (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
CREATE TABLE winners (
id INT AUTO_INCREMENT PRIMARY KEY,
prize_id INT,
participant_id INT,
FOREIGN KEY (prize_id) REFERENCES prizes(id),
FOREIGN KEY (participant_id) REFERENCES participants(id)
);$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "lottery_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}$sql = "SELECT * FROM prizes";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "Prize: " . $row["name"] . "<br>";
}if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO participants (name, email) VALUES ('$name', '$email')";
$conn->query($sql);
}$random_prize_sql = "SELECT * FROM prizes ORDER BY RAND() LIMIT 1";
$random_prize_result = $conn->query($random_prize_sql);
$random_prize = $random_prize_result->fetch_assoc();
$random_participant_sql = "SELECT * FROM participants ORDER BY RAND() LIMIT 1";
$random_participant_result = $conn->query($random_participant_sql);
$random_participant = $random_participant_result->fetch_assoc();
$sql = "INSERT INTO winners (prize_id, participant_id) VALUES ('" . $random_prize['id'] . "', '" . $random_participant['id'] . "')";
$conn->query($sql);
echo "Congratulations! Prize: " . $random_prize['name'] . " Winner: " . $random_participant['name'];Design the front-end page according to your needs to display the prize list and the lottery participation form, and interact with the back-end PHP code via the form submission to implement the lottery function.
With the steps and example code above, we have implemented a complete PHP lottery function. In real projects, you can add more lottery rules, optimize database structures, and enhance the interface design to make the lottery feature more complete and engaging. This guide aims to help developers easily build a PHP lottery system.