PHP and MySQL practical exercises
1. A E-commerce application
Database:
CREATE DATABASE ecommerce_store;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
role ENUM('customer', 'admin') NOT NULL
);
-- Products Table
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
image VARCHAR(255)
);
-- Shopping Cart Table
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
product_id INT,
quantity INT,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
db.php:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'ecommerce_store';
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Register.php:
<?php
include('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); // Encrypt password
$role = 'customer'; // Default role
$query = "INSERT INTO users (username, password, role) VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("sss", $username, $password, $role);
if ($stmt->execute()) {
echo "Registration successful!";
} else {
echo "Error: " . $stmt->error;
}
}
?>
<form method="post" action="register.php">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Register">
</form>
Login.php:
<?php
session_start();
include('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
echo "Login successful!";
header("Location: index.php");
} else {
echo "Invalid username or password.";
}
}
?>
<form method="post" action="login.php">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
Logout.php:
<?php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
exit();
?>
Index.php:
<?php
include('db.php');
$result = $conn->query("SELECT * FROM products");
while ($product = $result->fetch_assoc()) {
echo "<div>";
echo "<h3>" . $product['name'] . "</h3>";
echo "<p>" . $product['description'] . "</p>";
echo "<p>$" . $product['price'] . "</p>";
echo "<a href='add_to_cart.php?id=" . $product['id'] . "'>Add to Cart</a>";
echo "</div>";
}
?>
Add_to_cart.php:
<?php
session_start();
include('db.php');
if (isset($_GET['id'])) {
$product_id = $_GET['id'];
$user_id = $_SESSION['user_id'];
// Check if the product is already in the cart
$query = "SELECT * FROM cart WHERE user_id = ? AND product_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $user_id, $product_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// Update the quantity
$stmt = $conn->prepare("UPDATE cart SET quantity = quantity + 1 WHERE user_id = ?
AND product_id = ?");
$stmt->bind_param("ii", $user_id, $product_id);
$stmt->execute();
} else {
// Add the product to the cart
$stmt = $conn->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES
(?, ?, 1)");
$stmt->bind_param("ii", $user_id, $product_id);
$stmt->execute();
}
header("Location: cart.php");
}
?>
Cart.php:
<?php
session_start();
include('db.php');
$user_id = $_SESSION['user_id'];
$query = "SELECT cart.*, products.name, products.price FROM cart JOIN products ON
cart.product_id = products.id WHERE cart.user_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$total = 0;
while ($item = $result->fetch_assoc()) {
echo "<div>";
echo "<p>" . $item['name'] . " - $" . $item['price'] . " x " . $item['quantity'] .
"</p>";
echo "</div>";
$total += $item['price'] * $item['quantity'];
}
echo "<h3>Total: $" . $total . "</h3>";
echo "<a href='checkout.php'>Proceed to Checkout</a>";
?>
Checkout.php:
<?php
session_start();
include('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Insert order into orders table (simplified)
$user_id = $_SESSION['user_id'];
$total = $_POST['total'];
$query = "INSERT INTO orders (user_id, total) VALUES (?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("id", $user_id, $total);
$stmt->execute();
// Clear cart after checkout
$stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
echo "Thank you for your order!";
}
$query = "SELECT SUM(products.price * cart.quantity) AS total FROM cart JOIN products ON
cart.product_id = products.id WHERE cart.user_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>
<form method="post" action="checkout.php">
<h3>Total: $<?php echo $row['total']; ?></h3>
<input type="hidden" name="total" value="<?php echo $row['total']; ?>">
<input type="submit" value="Confirm Order">
</form>
Admin_panel.php:
<?php
session_start();
include('db.php');
// Check if the user is an admin
if ($_SESSION['role'] !== 'admin') {
echo "Access denied.";
exit();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$image = $_POST['image'];
$query = "INSERT INTO products (name, description, price, image) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("ssds", $name, $description, $price, $image);
if ($stmt->execute()) {
echo "Product added!";
} else {
echo "Error: " . $stmt->error;
}
}
?>
<form method="post" action="admin_panel.php">
Product Name: <input type="text" name="name" required><br>
Description: <input type="text" name="description"><br>
Price: <input type="number" name="price" step="0.01" required><br>
Image URL: <input type="text" name="image"><br>
<input type="submit" value="Add Product">
</form>
2. A simple Contact Management System:
Database:
CREATE DATABASE contact_management;
CREATE TABLE contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(15) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Db.php:
<?php
$servername = "localhost";
$username = "root"; // Change to your MySQL username
$password = ""; // Change to your MySQL password
$dbname = "contact_management";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Add_contact.php:
<?php
include('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$sql = "INSERT INTO contacts (first_name, last_name, email, phone)
VALUES ('$first_name', '$last_name', '$email', '$phone')";
if ($conn->query($sql) === TRUE) {
echo "New contact added successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<form action="add_contact.php" method="POST">
<label>First Name:</label><br>
<input type="text" name="first_name" required><br>
<label>Last Name:</label><br>
<input type="text" name="last_name" required><br>
<label>Email:</label><br>
<input type="email" name="email" required><br>
<label>Phone:</label><br>
<input type="text" name="phone" required><br>
<button type="submit">Add Contact</button>
</form>
View_contacts.php:
<?php
include('db.php');
$sql = "SELECT * FROM contacts";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["first_name"]. " " .
$row["last_name"]. " - Email: " . $row["email"]. " - Phone: " . $row["phone"]. "<br>";
echo "<a href='edit_contact.php?id=" . $row["id"] . "'>Edit</a> | ";
echo "<a href='delete_contact.php?id=" . $row["id"] . "'>Delete</a><br><br>";
}
} else {
echo "No contacts found.";
}
?>
Edit_contacts.php:
<?php
include('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$sql = "UPDATE contacts SET first_name='$first_name', last_name='$last_name',
email='$email', phone='$phone' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Contact updated successfully";
} else {
echo "Error: " . $conn->error;
}
}
$id = $_GET['id'];
$sql = "SELECT * FROM contacts WHERE id=$id";
$result = $conn->query($sql);
$contact = $result->fetch_assoc();
?>
<form action="edit_contact.php" method="POST">
<input type="hidden" name="id" value="<?php echo $contact['id']; ?>">
<label>First Name:</label><br>
<input type="text" name="first_name" value="<?php echo $contact['first_name']; ?>"
required><br>
<label>Last Name:</label><br>
<input type="text" name="last_name" value="<?php echo $contact['last_name']; ?>"
required><br>
<label>Email:</label><br>
<input type="email" name="email" value="<?php echo $contact['email']; ?>"
required><br>
<label>Phone:</label><br>
<input type="text" name="phone" value="<?php echo $contact['phone']; ?>" required><br>
<button type="submit">Update Contact</button>
</form>
Delete_contacts.php:
<?php
include('db.php');
$id = $_GET['id'];
$sql = "DELETE FROM contacts WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Contact deleted successfully";
} else {
echo "Error: " . $conn->error;
}
header('Location: view_contacts.php'); // Redirect back to view contacts
?>
Search_contacts.php:
<?php
include('db.php');
$search_term = isset($_POST['search_term']) ? $_POST['search_term'] : '';
$sql = "SELECT * FROM contacts WHERE first_name LIKE '%$search_term%' OR last_name LIKE
'%$search_term%' OR email LIKE '%$search_term%'";
$result = $conn->query($sql);
?>
<form action="search_contacts.php" method="POST">
<label>Search Contacts:</label><br>
<input type="text" name="search_term" value="<?php echo $search_term; ?>"
placeholder="Search by name or email" required><br>
<button type="submit">Search</button>
</form>
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["first_name"]. " " .
$row["last_name"]. " - Email: " . $row["email"]. " - Phone: " . $row["phone"]. "<br>";
}
} else {
echo "No contacts found.";
}
?>
3. A simple library management system:
Database:
CREATE DATABASE library_system;
USE library_system;
CREATE TABLE books (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
year INT(4) NOT NULL,
isbn VARCHAR(20) NOT NULL
);
Db.php:
<?php
$servername = "localhost";
$username = "root"; // Change to your MySQL username
$password = ""; // Change to your MySQL password
$dbname = "library_system";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Index.php:
<?php
include 'db.php';
$sql = "SELECT * FROM books";
$stmt = $conn->query($sql);
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Library Management System</title>
</head>
<body>
<h1>Library Management System</h1>
<a href="add.php">Add New Book</a>
<table border="1">
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>ISBN</th>
<th>Actions</th>
</tr>
<?php foreach ($books as $book): ?>
<tr>
<td><?php echo $book['id']; ?></td>
<td><?php echo $book['title']; ?></td>
<td><?php echo $book['author']; ?></td>
<td><?php echo $book['year']; ?></td>
<td><?php echo $book['isbn']; ?></td>
<td>
<a href="edit.php?id=<?php echo $book['id']; ?>">Edit</a> |
<a href="delete.php?id=<?php echo $book['id']; ?>" onclick="return
confirm('Are you sure?')">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
Add.php:
<?php
include 'db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = $_POST['title'];
$author = $_POST['author'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
$sql = "INSERT INTO books (title, author, year, isbn) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->execute([$title, $author, $year, $isbn]);
header('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add New Book</title>
</head>
<body>
<h1>Add New Book</h1>
<form action="add.php" method="POST">
<label>Title:</label><br>
<input type="text" name="title" required><br><br>
<label>Author:</label><br>
<input type="text" name="author" required><br><br>
<label>Year:</label><br>
<input type="number" name="year" required><br><br>
<label>ISBN:</label><br>
<input type="text" name="isbn" required><br><br>
<input type="submit" value="Add Book">
</form>
<br>
<a href="index.php">Back to list</a>
</body>
</html>
Edit.php:
<?php
include 'db.php';
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM books WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$id]);
$book = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$book) {
echo "Book not found!";
exit;
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = $_POST['title'];
$author = $_POST['author'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
$sql = "UPDATE books SET title = ?, author = ?, year = ?, isbn = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$title, $author, $year, $isbn, $id]);
header('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Book</title>
</head>
<body>
<h1>Edit Book</h1>
<form action="edit.php?id=<?php echo $book['id']; ?>" method="POST">
<label>Title:</label><br>
<input type="text" name="title" value="<?php echo $book['title']; ?>"
required><br><br>
<label>Author:</label><br>
<input type="text" name="author" value="<?php echo $book['author']; ?>"
required><br><br>
<label>Year:</label><br>
<input type="number" name="year" value="<?php echo $book['year']; ?>"
required><br><br>
<label>ISBN:</label><br>
<input type="text" name="isbn" value="<?php echo $book['isbn']; ?>"
required><br><br>
<input type="submit" value="Update Book">
</form>
<br>
<a href="index.php">Back to list</a>
</body>
</html>
Delete.php:
<?php
include 'db.php';
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "DELETE FROM books WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$id]);
header('Location: index.php');
exit;
} else {
echo "Invalid book ID.";
exit;
}
?>