Assignments On Class 39:
Real-World Project - Part 1 (Only Concept)
Here are some assignments based on the concepts from the Real-World Project - Part 1 (Online Store project). These assignments will help students apply the knowledge gained and build a foundation for working with real-world PHP projects.
Assignment
1: Setting Up the Environment and Database
Objective:
Set up the project environment and create the necessary database tables for the
online store project.
Tasks:
1. Set up a
local development environment using XAMPP, WAMP, or any preferred local server.
2. Create a
MySQL database for the online store and connect it with a PHP project.
3. Create
the following tables:
o
products (id, name, description, price, image)
o
orders (id, user_id, address, created_at)
o
order_items (id, order_id, product_id)
4. Create a db.php file for
handling the database connection.
5. Create a
simple page (index.php) that displays a connection success or failure
message based on the database connection.
Deliverables:
- PHP
file for database connection (db.php).
- SQL
script for creating the required tables (create_tables.sql).
- Screenshot
or code of the setup page displaying connection success.
Assignment
2: Displaying Products (Product Listing Page)
Objective:
Create a page to display all products in the database on the front-end.
Tasks:
1. Use the products table to
retrieve product information (name, description, price, image) and display them
in a list on the web page.
2. Implement
basic HTML and CSS to display the product images in a grid layout.
3. Add links
to each product to allow users to add products to their shopping cart (use the add_to_cart.php script).
4. If no
products are found in the database, display a message saying "No products
available".
Deliverables:
- PHP
page (products.php) to display products.
- Screenshot
or code of the product listing page showing products.
Assignment
3: Implementing Add to Cart Functionality
Objective:
Create a simple shopping cart system that allows users to add products to their
cart.
Tasks:
1. Create an
add_to_cart.php script
that:
o
Adds a product to the shopping cart (using PHP
sessions).
o
Checks if the product is already in the cart and
prevents duplicates.
2. Create a cart.php page to:
o
Display the products currently in the cart.
o
Show product details (name, description, price,
quantity).
o
Display the total price of all items in the cart.
o
Allow users to remove items from the cart.
Deliverables:
- PHP
script (add_to_cart.php) to add products to the cart.
- PHP
page (cart.php) to display the shopping cart.
- Screenshot
or code of the cart page showing added products.
Assignment
4: Implementing Checkout Functionality
Objective:
Implement a checkout page where users can enter their shipping address and
place an order.
Tasks:
1. Create a checkout.php page
that:
o
Displays a form where users can enter their
shipping address.
o
Displays the total amount to be paid based on the
products in the cart.
2. When the
form is submitted, create a process_checkout.php script that:
o
Saves the order details (user ID, shipping address)
in the orders table.
o
Saves the order items (product ID) in the order_items table.
o
Clears the shopping cart session after the order is
placed.
3. Display a
success message upon successful checkout, or an error message if the checkout
fails.
Deliverables:
- PHP
page (checkout.php) for entering shipping details.
- PHP
script (process_checkout.php) for processing the order.
- Screenshot
or code of the checkout page showing the form and order success message.
Assignment
5: Admin Panel for Product Management
Objective:
Create an admin panel to allow admins to add, edit, and delete products.
Tasks:
1. Create an
admin/products.php page
where:
o
Admins can view a list of all products from the
database.
o
Admins can add a new product using a form (name, description, price, image).
o
Admins can edit and delete existing products.
2. Implement
functionality to delete a product from the database.
3. Implement
a basic authentication system for the admin panel (check if the user is logged
in as an admin before accessing the page).
Deliverables:
- PHP
page (admin/products.php) to manage products.
- PHP
scripts for adding, editing, and deleting products.
- Screenshot
or code showing the admin panel functionality (product list, form to
add/edit products).
Assignment
6: Implementing Image Upload for Products
Objective:
Allow admins to upload product images when adding or editing a product.
Tasks:
1. Update
the add_product.php page to
include a file input field for uploading images.
2. Modify
the add_product.php and edit_product.php scripts
to handle file uploads:
o
Ensure the uploaded file is an image (JPG, PNG,
GIF).
o
Store the uploaded image in a specific directory
(e.g., assets/images).
o
Store the image file name in the products table.
3. Display
the uploaded image in the product list and individual product pages.
Deliverables:
- Modified
add_product.php to
allow image uploads.
- Script
to process image uploads (upload_image.php or inside add_product.php).
- Screenshot
or code showing the product with an uploaded image.
Assignment
7: Displaying Order History
Objective:
Create a page where users can view their past orders.
Tasks:
1. Create a order_history.php page
that:
o
Retrieves all past orders from the orders table
for the logged-in user.
o
Displays the order ID, shipping address, and total
price of each order.
o
Links to view the details of each order (products
in the order).
2. Create a view_order.php page
that shows the products in a specific order (order ID from order_items table).
Deliverables:
- PHP
page (order_history.php) for displaying past orders.
- PHP
page (view_order.php) for displaying the details of an order.
- Screenshot
or code showing the order history and order details.
Bonus
Assignment: Implementing Payment Gateway Integration
Objective:
Integrate a payment gateway (e.g., PayPal, Stripe) for processing payments.
Tasks:
1. Research
and integrate a simple payment gateway into your checkout process.
2. Modify
the checkout.php page to
allow users to proceed to the payment page after entering their shipping
details.
3. Handle
the payment response (success or failure) and display a confirmation or failure
message accordingly.
Deliverables:
- Integration
code for payment gateway (e.g., PayPal API).
- Modified
checkout.php to
include payment processing.
- Screenshot
or code showing successful payment integration.
Evaluation
Criteria:
- Correct
implementation of functionality.
- Code
structure and organization.
- Proper
use of HTML, CSS, and PHP.
- Error
handling and user input validation.
- Adherence
to project requirements.
These assignments allow students
to progressively build and enhance the Online Store project while
gaining hands-on experience with essential PHP, MySQL, and web development
concepts.
4o mini
You said:
WRITE SOME ASSIGNMENTS FROM ABOVE
CONCEPT WITH STEP BY STEP SOLUTIONS with explanation
ChatGPT
said:
ChatGPT
Here are some assignments from
the Real-World PHP Project - Online Store concept, with step-by-step
solutions and explanations for each task.
Assignment
1: Setting Up the Environment and Database
Objective:
Set up the project environment and create the necessary database tables for the
online store project.
Step-by-Step
Solution:
1. Set up
the Local Development Environment:
o
Install a local server like XAMPP (Windows)
or MAMP (Mac) or WAMP (Windows).
o
Start the Apache and MySQL services from the
control panel.
o
Access the phpMyAdmin page by visiting http://localhost/phpmyadmin.
2. Create
the Database and Tables:
o
Open phpMyAdmin and create a new database
called online_store.
o
In the SQL tab, write the SQL queries to create
tables. Here’s the code for creating the necessary tables:
sql
Copy code
-- Create products table
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
price DECIMAL(10, 2) NOT NULL,
image VARCHAR(255) NOT NULL
);
-- Create orders table
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
address TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Create order_items table
CREATE TABLE order_items (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
product_id INT NOT NULL,
FOREIGN KEY (order_id) REFERENCES
orders(id),
FOREIGN KEY (product_id) REFERENCES
products(id)
);
3. Database
Connection Setup (PHP):
o
Create a db.php file to manage the database
connection in your PHP project.
o
Use PHP’s mysqli to connect to the database.
php
Copy code
<?php
// db.php - Database Connection
Script
$host = 'localhost'; // Database host
$user = 'root'; // Database username (default for XAMPP)
$pass = ''; // Database password (default for
XAMPP is empty)
$db_name = 'online_store'; //
Database name
// Create connection
$conn = mysqli_connect($host, $user,
$pass, $db_name);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
Assignment
2: Displaying Products (Product Listing Page)
Objective:
Create a page to display all products in the database on the front-end.
Step-by-Step
Solution:
1. Display
All Products:
o
Create a PHP file products.php that will retrieve and display
products from the products table.
2. HTML
Layout and PHP Integration:
o
Use a simple HTML structure to display products in
a grid. For each product, display its name, description, price, and image.
php
Copy code
<?php
// Include the database
connection
include('db.php');
// SQL query to fetch all
products
$sql = "SELECT * FROM
products";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) >
0) {
// Output each product in a grid
echo '<div
class="product-list">';
while($row = mysqli_fetch_assoc($result)) {
echo '<div
class="product">';
echo '<h2>' . $row['name'] . '</h2>';
echo '<p>' . $row['description']
. '</p>';
echo '<p>Price: $' . $row['price']
. '</p>';
echo '<img src="images/' . $row['image']
. '" alt="' . $row['name'] . '">';
echo '<button>Add to
Cart</button>';
echo '</div>';
}
echo '</div>';
} else {
echo "No products available.";
}
// Close connection
mysqli_close($conn);
?>
3. Styling
(CSS):
o
You can add CSS to style the product grid and make
the images look appealing.
css
Copy code
.product-list {
display: flex;
flex-wrap: wrap;
}
.product {
width: 200px;
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
text-align: center;
}
.product img {
width: 100%;
height: auto;
}
Assignment
3: Implementing Add to Cart Functionality
Objective:
Create a simple shopping cart system that allows users to add products to their
cart.
Step-by-Step
Solution:
1. Start a
PHP Session:
o
Start a session at the beginning of your PHP file
so that the cart can be stored in the session.
php
Copy code
session_start();
2. Add to
Cart Logic:
o
Create an add_to_cart.php file. This will receive the product_id and add
the product to the cart.
php
Copy code
<?php
session_start();
// Check if the product_id is
passed in the URL
if (isset($_GET['product_id'])) {
$product_id = $_GET['product_id'];
// Check if the cart already exists in
session, otherwise create an empty cart
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// Add the product to the cart
$_SESSION['cart'][] = $product_id;
// Redirect back to the products page
header("Location: products.php");
}
?>
3. Display
Cart Contents:
o
Create a cart.php file to display the contents of
the cart.
php
Copy code
<?php
session_start();
include('db.php');
// Check if the cart is empty
if (!isset($_SESSION['cart']) || empty($_SESSION['cart']))
{
echo "Your cart is empty.";
} else {
// Retrieve product details from the cart
$cart = $_SESSION['cart'];
$product_ids = implode(',', $cart); // Convert
array to string for SQL query
// Fetch product details
$sql = "SELECT * FROM products WHERE
id IN ($product_ids)";
$result = mysqli_query($conn, $sql);
echo '<div class="cart">';
while ($row = mysqli_fetch_assoc($result))
{
echo
'<div class="cart-item">';
echo '<p>' . $row['name'] . '</p>';
echo '<p>Price: $' . $row['price']
. '</p>';
echo '</div>';
}
echo '</div>';
}
// Close connection
mysqli_close($conn);
?>
4. Testing:
o
Test the add-to-cart functionality by clicking the
"Add to Cart" button for each product. Verify that the products are
added to the cart and displayed correctly.
Assignment
4: Implementing Checkout Functionality
Objective:
Implement a checkout page where users can enter their shipping address and
place an order.
Step-by-Step
Solution:
1. Create
the Checkout Form:
o
In the checkout.php file, create a form to allow
users to enter their shipping details.
php
Copy code
<?php
session_start();
include('db.php');
// Display the cart
if (isset($_SESSION['cart'])
&& !empty($_SESSION['cart'])) {
// Form for shipping details
echo '<form
action="process_checkout.php" method="POST">';
echo '<label for="address">Enter
Shipping Address:</label>';
echo '<textarea name="address"
required></textarea>';
echo '<button
type="submit">Place Order</button>';
echo '</form>';
} else {
echo "Your cart is empty. Add products
to your cart before proceeding.";
}
?>
2. Process
the Order:
o
Create a process_checkout.php file to process the order and
save it in the database.
php
Copy code
<?php
session_start();
include('db.php');
// Check if address is provided
if (isset($_POST['address'])
&& !empty($_POST['address'])) {
$address = $_POST['address'];
$user_id = 1; // Assuming user ID 1 for now
(you could use a session variable for logged-in users)
// Insert the order into the orders table
$sql = "INSERT INTO orders (user_id,
address) VALUES ('$user_id', '$address')";
if (mysqli_query($conn, $sql)) {
// Get the last inserted order ID
$order_id = mysqli_insert_id($conn);
// Add items to the order_items table
foreach ($_SESSION['cart'] as $product_id)
{
$sql = "INSERT INTO
order_items (order_id, product_id) VALUES ('$order_id', '$product_id')";
mysqli_query($conn, $sql);
}
// Clear the cart after placing the
order
unset($_SESSION['cart']);
// Redirect to a confirmation page
header("Location:
order_confirmation.php?order_id=$order_id");
} else {
echo "Error placing order: "
. mysqli_error($conn);
}
} else {
echo "Address is required.";
}
// Close connection
mysqli_close($conn);
?>
3. Order
Confirmation:
o
Create a simple order_confirmation.php page to
display the order confirmation after checkout.
php
Copy code
<?php
$order_id = $_GET['order_id'];
echo "Your order has been
placed successfully. Order ID: $order_id";
?>
These assignments guide students
through building core functionality for the Online Store project. Each
assignment gradually introduces important concepts, starting from setting up
the database to implementing critical features such as product listing,
shopping cart, and checkout.
4o mini
You said:
more
ChatGPT
said:
ChatGPT
Here are more assignments with
detailed solutions and explanations based on the concept of building a Real-World
PHP Project for an Online Store:
Assignment
5: Implementing User Registration and Login
Objective:
Create a user registration and login system for the online store project,
allowing users to register, log in, and maintain their session.
Step-by-Step
Solution:
1. Create
the User Registration Form (register.php):
o
This form will collect the user’s name, email, and
password to create an account.
php
Copy code
<?php
include('db.php');
if ($_SERVER['REQUEST_METHOD'] ==
'POST') {
// Collect form data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn,
$_POST['password']);
// Hash the password for security
$hashed_password = password_hash($password,
PASSWORD_DEFAULT);
// Insert user data into the users table
$sql = "INSERT INTO users (name,
email, password) VALUES ('$name', '$email', '$hashed_password')";
if (mysqli_query($conn,
$sql)) {
echo "Registration successful!
<a href='login.php'>Login here</a>";
} else {
echo "Error: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
<form method="POST"
action="register.php">
<label>Name:</label>
<input type="text" name="name"
required><br>
<label>Email:</label>
<input type="email" name="email"
required><br>
<label>Password:</label>
<input type="password" name="password"
required><br>
<button type="submit">Register</button>
</form>
2. Create
the Login Form (login.php):
o
This form will ask for the user's email and
password for authentication.
php
Copy code
<?php
session_start();
include('db.php');
if ($_SERVER['REQUEST_METHOD'] ==
'POST') {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn,
$_POST['password']);
// SQL query to find user by email
$sql = "SELECT * FROM users WHERE
email = '$email'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// User exists, verify password
$user = mysqli_fetch_assoc($result);
if (password_verify($password, $user['password']))
{
// Store user session data
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
echo "Login successful!
Welcome, " . $_SESSION['user_name'] . ". <a
href='logout.php'>Logout</a>";
} else {
echo "Incorrect
password.";
}
} else {
echo "No user found with that
email address.";
}
}
mysqli_close($conn);
?>
<form method="POST"
action="login.php">
<label>Email:</label>
<input type="email" name="email"
required><br>
<label>Password:</label>
<input type="password" name="password"
required><br>
<button type="submit">Login</button>
</form>
3. Logout
(logout.php):
o
Create a file to log users out by destroying their
session.
php
Copy code
<?php
session_start();
session_unset();
session_destroy();
header("Location:
login.php");
?>
4. Testing:
o
Register a new user, then log in using the
credentials. Once logged in, users should be redirected to a dashboard page or
their profile.
Assignment
6: Implementing Product Search Functionality
Objective:
Allow users to search for products by name or description on the online store.
Step-by-Step
Solution:
1. Create
the Search Form (search.php):
o
Provide a search input field for users to search
for products by name.
php
Copy code
<form method="GET"
action="search.php">
<label>Search Products:</label>
<input type="text" name="search"
placeholder="Search by product name or description">
<button type="submit">Search</button>
</form>
2. Display
Search Results:
o
In search.php, retrieve the search term from
the query string and fetch matching products from the database.
php
Copy code
<?php
include('db.php');
if (isset($_GET['search'])) {
$search_term = mysqli_real_escape_string($conn,
$_GET['search']);
// SQL query to search for products by name
or description
$sql = "SELECT * FROM products WHERE
name LIKE '%$search_term%' OR description LIKE '%$search_term%'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo '<div
class="search-results">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<div
class="product">';
echo '<h2>' . $row['name'] . '</h2>';
echo '<p>' . $row['description']
. '</p>';
echo '<p>Price: $' . $row['price']
. '</p>';
echo '</div>';
}
echo '</div>';
} else {
echo "No products found matching
your search.";
}
}
mysqli_close($conn);
?>
3. Testing:
o
Test the search functionality by searching for
products by name or description. Ensure it returns the correct results.
Assignment
7: Implementing Order History for Users
Objective:
Allow users to view their past orders on their profile page.
Step-by-Step
Solution:
1. Create an
Order History Page (order_history.php):
o
This page will show all past orders placed by the
user.
php
Copy code
<?php
session_start();
include('db.php');
// Ensure user is logged in
if (!isset($_SESSION['user_id']))
{
echo "Please log in to view your order
history.";
exit();
}
$user_id = $_SESSION['user_id'];
// SQL query to retrieve orders
placed by the user
$sql = "SELECT * FROM orders
WHERE user_id = '$user_id' ORDER BY created_at DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) >
0) {
echo '<h2>Your Order
History</h2>';
echo '<table>';
echo '<tr><th>Order
ID</th><th>Address</th><th>Date</th><th>Status</th></tr>';
while ($order = mysqli_fetch_assoc($result))
{
echo '<tr>';
echo '<td>' . $order['id'] . '</td>';
echo '<td>' . $order['address'] .
'</td>';
echo '<td>' . $order['created_at']
. '</td>';
echo '<td>Completed</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "You have not placed any orders
yet.";
}
mysqli_close($conn);
?>
2. Testing:
o
Log in as a user who has placed an order and view
the order history. Ensure that the list of past orders is displayed correctly.
Assignment
8: Implementing Admin Panel for Managing Products
Objective:
Create an admin panel that allows the admin to add, update, and delete
products.
Step-by-Step
Solution:
1. Create
Admin Panel (admin_panel.php):
o
This page will allow the admin to manage products.
php
Copy code
<?php
session_start();
include('db.php');
// Check if the user is logged in
as admin
if (!isset($_SESSION['user_id'])
|| $_SESSION['role'] != 'admin') {
echo "Access denied. Only admins can
manage products.";
exit();
}
// Display form to add a new
product
echo '<h2>Add New
Product</h2>';
echo '<form
method="POST" action="admin_panel.php" enctype="multipart/form-data">
<label>Product
Name:</label><br>
<input type="text"
name="name" required><br>
<label>Description:</label><br>
<textarea name="description"
required></textarea><br>
<label>Price:</label><br>
<input type="text" name="price"
required><br>
<label>Image:</label><br>
<input type="file"
name="image" required><br>
<button type="submit"
name="add_product">Add Product</button>
</form>';
if (isset($_POST['add_product']))
{
$name = mysqli_real_escape_string($conn, $_POST['name']);
$description = mysqli_real_escape_string($conn,
$_POST['description']);
$price = mysqli_real_escape_string($conn, $_POST['price']);
$image = $_FILES['image']['name'];
// Upload image
move_uploaded_file($_FILES['image']['tmp_name'],
'images/' . $image);
// SQL query to insert the new product
$sql = "INSERT INTO products (name,
description, price, image) VALUES ('$name', '$description', '$price', '$image')";
if (mysqli_query($conn, $sql)) {
echo
"Product added successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
2. Testing:
o
Log in as an admin, navigate to the admin panel,
and try adding a new product. Make sure it appears in the product list on the
front end.
Conclusion:
These assignments will help
students gain hands-on experience with fundamental features of a real-world PHP
project such as user registration and login, product search, order
history, and admin panel management. Students will be able to plan,
structure, and implement a complete online store project by following these
steps.