Building an Online Voting System using PHP and MySQL

0
88

Creating an online voting system is a fun way to explore web development concepts like PHP form handling, MySQL database integration, and Bootstrap styling. In this tutorial, we will create a voting platform where users can vote between two candidates: Donald Trump and Kamala Harris. We will also display live voting results with a visually appealing interface.

Project Overview

We’ll implement:

  • A user interface with Bootstrap for a modern look.
  • Database integration using MySQL.
  • Secure form submission with prepared statements.

Follow this video for complete guidance :

Complete Source Code

<?php
// Database Connection
$host = "localhost";
$user = "root";   
$pass = "";       
$dbname = "voting";
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Handle Voting
if (isset($_POST['candidate'])) {
    $candidate = $_POST['candidate'];
    $stmt = $conn->prepare("UPDATE votes SET vote_count = vote_count + 1 WHERE candidate = ?");
    $stmt->bind_param("s", $candidate);
    $stmt->execute();
}

// Fetch Results
$results = $conn->query("SELECT * FROM votes")->fetch_all(MYSQLI_ASSOC);
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Voting</title>

	<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
	<style type="text/css">
		body{
			background: #000;
		}
		h1{
			text-align: center;
			margin-bottom: 50px;
			font-weight: bold;
		}
		figure{
			margin-bottom: 0px;
			box-shadow: 3px 5px 10px rgba(0,0,0,.5);
		}
		button{
			border-radius: 0!important;
		}
		.votes .vote-count{
			font-weight: bold;
			font-size:44px;
			line-height: 1em;	
		}
		.votes .vote-label{
			color:#555;
		}
	</style>
</head>
<body>
	<div class="container mt-5">
		<div class="row justify-content-center">
			<div class="col-md-6">
				<div class="card">
					<div class="card-body">
						<h1>Online Voting System</h1>
						<div class="row justify-space-between">
							<div class="col-md-6 px-5 py-2 republic">
								<form method="post">
									<figure>
										<img class="w-100" src="https://upload.wikimedia.org/wikipedia/commons/5/56/Donald_Trump_official_portrait.jpg">
									</figure>
									<button class="btn btn-danger w-100" type="submit" name="candidate" value="Trump">
										Vote for Trump
									</button>
									<div class="votes mt-3 text-center">
										<div class="vote-count"><?php echo $results[0]['vote_count'];?></div>
										<span class="vote-label">votes</span>
									</div>
								</form>
							</div>
							<div class="col-md-6 px-5 py-2 democrat">
								<form method="post">
									<figure>
										<img class="w-100" src="https://upload.wikimedia.org/wikipedia/commons/4/41/Kamala_Harris_Vice_Presidential_Portrait.jpg">
									</figure>
									<button class="btn btn-primary w-100" type="submit" name="candidate" value="Harris">
											Vote for Kamala
									</button>
									<div class="votes mt-3 text-center">
										<div class="vote-count"><?php echo $results[1]['vote_count'];?></div>
										<span class="vote-label">votes</span>
									</div>
								</form>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>

Database Setup

Create a MySQL database named voting and run this SQL query:]

CREATE TABLE votes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    candidate VARCHAR(50) NOT NULL,
    vote_count INT DEFAULT 0
);

-- Insert initial values
INSERT INTO votes (candidate, vote_count) VALUES ('Trump', 0), ('Harris', 0);

Step 3: Design and Logic

We’ll use Bootstrap for a clean and responsive design. Here are the features:

  • Form Submission: A simple form where users select a candidate.
  • Database Interaction: Update and fetch results from the votes table.
  • Results Display: Show live vote counts below each candidate.
ALSO READ  QR Code Reader using PHP Library

Key Features Breakdown

  • Database Connection: We connect to MySQL using mysqli.
  • Vote Submission: When a user submits the form, we securely update the database using prepared statements.
  • Real-Time Results Display: The system queries the database and displays the updated vote count.

Enhancements You Can Try

  • Authentication: Add user login functionality to prevent multiple votes.
  • Confirmation Messages: Show confirmation pop-ups using JavaScript.
  • Security Enhancements: Use CSRF tokens to secure form submissions.

This project demonstrates how to build a simple but functional online voting system using PHP and MySQL. It covers essential web development skills, including working with forms, connecting to databases, and using Bootstrap for modern design.

Happy Coding! 🚀

Comments are closed.