In the digital age, online voting systems have become essential for conducting secure and efficient elections. This article guides you through the process of building an Online Voting System using PHP and MySQL, providing both code snippets and MySQL queries.
Prerequisites: Before starting, ensure you have a web server with PHP and MySQL installed. You can use tools like XAMPP, WampServer, or MAMP for local development.
Step 1: Database Setup Begin by creating a MySQL database named voting_system
. Execute the following SQL query:
CREATE DATABASE IF NOT EXISTS voting_system;
USE voting_system;
Step 2: Create Tables
Create two tables for candidates and votes using the following queries:
CREATE TABLE candidates (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
party VARCHAR(50) NOT NULL
);
CREATE TABLE votes (
id INT AUTO_INCREMENT PRIMARY KEY,
candidate_id INT,
FOREIGN KEY (candidate_id) REFERENCES candidates(id)
);
Step 3: PHP Connection
Create a PHP file (db.php
) to handle the database connection:
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "voting_system";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Step 4: Candidate Registration Form
Create a PHP file (register_candidate.php
) for candidate registration:
<?php
include("db.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$party = $_POST["party"];
$sql = "INSERT INTO candidates (name, party) VALUES ('$name', '$party')";
if ($conn->query($sql) === TRUE) {
echo "Candidate registered successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
Step 5: Voting Form
Create a PHP file (vote.php
) for the voting form:
<?php
include("db.php");
$candidates = $conn->query("SELECT * FROM candidates");
if ($candidates->num_rows > 0) {
while ($row = $candidates->fetch_assoc()) {
echo "<input type='radio' name='candidate' value='" . $row["id"] . "'>" . $row["name"] . "<br>";
}
} else {
echo "No candidates available.";
}
?>
Step 6: Vote Submission
Create a PHP file (submit_vote.php
) to handle vote submission:
<?php
include("db.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$candidate_id = $_POST["candidate"];
$sql = "INSERT INTO votes (candidate_id) VALUES ('$candidate_id')";
if ($conn->query($sql) === TRUE) {
echo "Vote submitted successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
This article demonstrated the step-by-step process of building an Online Voting System with PHP and MySQL. From database setup to form handling, you now have a foundation to expand upon for a secure and functional voting application. Customize and enhance the system according to your specific requirements.