Welcome to the exciting world of PHP! In this tutorial, we'll create a Poll System from scratch. By the end, you'll have a functional polling application that you can use or modify for your own projects. Let's dive in!
PHP (Hypertext Preprocessor) is a popular server-side scripting language used for web development. It's free, open-source, and can be embedded within HTML.
Before we start, ensure you have a local web server installed (e.g., XAMPP, WAMP, or MAMP). Create a new folder for our project, and set up a new PHP file (index.php).
Our poll system will need a database. We'll use MySQL, which is commonly paired with PHP. Let's create a database and a table for storing polls and votes.
CREATE DATABASE poll_system;
USE poll_system;
CREATE TABLE polls (
id INT(11) NOT NULL AUTO_INCREMENT,
question VARCHAR(255) NOT NULL,
options TEXT NOT NULL,
votes INT(11) NOT NULL DEFAULT 0,
PRIMARY KEY (id)
);Now, let's create a form for users to participate in polls. We'll use HTML, PHP, and MySQLi (an improved version of MySQL for PHP).
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<!-- ... -->
<?php
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "poll_system");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch poll data
$sql = "SELECT * FROM polls";
$result = $conn->query($sql);
// Display polls if any
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h2>" . $row["question"] . "</h2>";
echo "<form action='vote.php' method='post'>";
$options = explode('|', $row["options"]);
foreach ($options as $option) {
echo "<input type='radio' name='option' value='" . $option . "'>" . $option . "<br>";
}
echo "<input type='hidden' name='poll_id' value='" . $row["id"] . "'>";
echo "<input type='submit' value='Vote'>";
echo "</form>";
}
}
?>
<!-- ... -->
</body>
</html>Next, we'll create a vote.php file that will handle the form submission and record the vote in the database.
<?php
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "poll_system");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get poll ID and chosen option
$poll_id = $_POST["poll_id"];
$option = $_POST["option"];
// Update votes in the database
$sql = "UPDATE polls SET votes = votes + 1 WHERE id = $poll_id";
$result = $conn->query($sql);
// Insert the vote into a separate table if needed
// Redirect back to the poll page
header("Location: index.php");Happy coding! If you found this tutorial helpful, don't forget to share it with others. π
Note: The provided code examples are simple and basic. In a real-world application, you may want to enhance security, error handling, and user management.
Pro Tip: To learn more about PHP, explore advanced topics like classes, inheritance, and object-oriented programming.
Keep up the great work, and see you in the next lesson! π