Build Online Stores in PHP

Rashmi Mishra
0

 

Build Online Stores in PHP

Project Overview: E-commerce Website

The E-commerce Website is a PHP and MySQL-based application designed to provide a complete online shopping experience.

The project includes two main panels: an Admin Panel for managing the website and a User Panel for customer interaction. It aims to implement basic e-commerce functionalities, including product management, cart functionality, and order checkout, while ensuring a user-friendly interface.


Goals of the Project

1.   For Admins:

o    Add, edit, and delete products.

o    Manage product information such as name, price, description, and images.

o    Maintain secure access to the admin panel using login authentication.

2.   For Users:

o    Browse a catalog of products.

o    Add products to a cart.

o    Proceed with checkout and confirm purchases.


Key Features

1.   Admin Panel:

o    Secure login for admins.

o    Dashboard for managing products.

o    Upload product images and details.

o    View the list of all products and perform CRUD (Create, Read, Update, Delete) operations.

2.   User Panel:

o    Browse products with detailed descriptions and pricing.

o    Add products to the cart and manage the cart (update quantities, remove items).

o    Checkout system for order placement.

o    Responsive design for an optimal browsing experience on various devices.

3.   Database Management:

o    Centralized MySQL database to store user, product, and cart data.

o    Relational structure to link users with their cart items and admin with product management.

4.   Security:

o    Secure user and admin authentication using hashed passwords.

o    Validation to prevent SQL injection and ensure proper data handling.


Technologies Used

1.   Backend: PHP for server-side scripting and business logic.

2.   Database: MySQL for storing data.

3.   Frontend:

o    HTML for structure.

o    CSS and Bootstrap for styling and responsiveness.

o    Basic JavaScript for interactivity (e.g., client-side form validation).

4.   Environment: Local development using XAMPP/WAMP.


Folder Structure Overview

  • Admin Panel: Files and pages specific to managing the website.
  • User Panel: Public-facing interface for browsing and shopping.
  • Database: Centralized connection and management for storing and retrieving data.
  • Uploads: Folder to store product images uploaded by the admin.

Target Users

1.   Admin: Website owner or operator responsible for managing inventory.

2.   User: Shoppers visiting the website to browse, add to the cart, and purchase products.


Use Cases

1.   Admin Use Case:

o    Logs into the admin panel using credentials.

o    Adds new products, edits existing ones, or deletes outdated ones.

o    Uploads product images for better visual representation.

2.   User Use Case:

o    Visits the website and browses the product catalog.

o    Adds desired products to the cart.

o    Proceeds to checkout and confirms the order.


 

Prerequisites

1.   Install XAMPP (or similar local server) for PHP and MySQL.

2.   A basic understanding of:

o    PHP

o    MySQL

o    HTML/CSS

o    Bootstrap (for styling)

3.   A text editor like VS Code.


1. Project Setup

1.   Create a Folder Structure:

ecommerce_project/

├── index.php                   # Landing page

├── login.php                   # Login page

├── register.php                # Registration page

├── admin_dashboard.php         # Admin dashboard

├── user_dashboard.php          # User dashboard

├── add_product.php             # Admin: Add new product

├── view_products.php           # Common: View all products

├── book_product.php            # User: Book a product

├── cart.php                    # User: View cart

├── checkout.php                # User: Checkout process

├── my_orders.php               # User: View order history

├── logout.php                  # Logout functionality

├── includes/

│   ├── admin_header.php        # Admin-specific header

│   ├── admin_sidebar.php       # Admin-specific sidebar

│   ├── admin_footer.php        # Admin-specific footer

│   ├── user_header.php         # User-specific header

│   ├── user_sidebar.php        # User-specific sidebar

│   ├── user_footer.php         # User-specific footer

│   ├── db.php                  # Database connection

│   └── auth.php                # Role-based access control

├── css/

│   └── style.css               # Styling for the application

└── uploads/

    └── images/                 # Store product images


2.   Start XAMPP Server:

o    Run Apache and MySQL from the XAMPP control panel.

o    Place the ecommerce/ folder in the htdocs/ directory.


2. Create the Database

1.   Access phpMyAdmin:

o    Open http://localhost/phpmyadmin.

2.   Create a Database:

CREATE DATABASE ecommerce_project;

3.   Create Tables:

the tables used in the e-commerce project, including tables for users, products, cart, orders, and order items.

1. Users Table

This table stores user information, such as their name, email, password, and role (admin or user).

CREATE TABLE users (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,

    email VARCHAR(100) NOT NULL UNIQUE,

    password VARCHAR(255) NOT NULL,

    role ENUM('admin', 'user') DEFAULT 'user',

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);

2. Products Table

This table stores product information such as the name, description, price, and image.

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),   -- Image path (e.g., 'uploads/images/product1.jpg')

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);

3. Cart Table

This table stores temporary cart items for users. It links users and products.

CREATE TABLE cart (

    id INT AUTO_INCREMENT PRIMARY KEY,

    user_id INT NOT NULL,

    product_id INT NOT NULL,

    quantity INT DEFAULT 1,

    FOREIGN KEY (user_id) REFERENCES users(id),

    FOREIGN KEY (product_id) REFERENCES products(id)

);

4. Orders Table

This table stores completed orders after checkout. It includes the total price of the order, the user who made the order, and the status of the order.

CREATE TABLE orders (

    id INT AUTO_INCREMENT PRIMARY KEY,

    user_id INT NOT NULL,

    total_price DECIMAL(10, 2) NOT NULL,

    order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    status ENUM('Pending', 'Shipped', 'Delivered') DEFAULT 'Pending',

    FOREIGN KEY (user_id) REFERENCES users(id)

);

5. Order Items Table

This table stores the details of the products in each order. It includes the product ID, quantity, and price at the time of order.

CREATE TABLE order_items (

    id INT AUTO_INCREMENT PRIMARY KEY,

    order_id INT NOT NULL,

    product_id INT NOT NULL,

    quantity INT NOT NULL,

    price DECIMAL(10, 2) NOT NULL,

    FOREIGN KEY (order_id) REFERENCES orders(id),

    FOREIGN KEY (product_id) REFERENCES products(id)

);

 

The main parts of the project are:

1.   User Registration and Login

2.   Admin Login and Product Management

3.   Displaying Products for Users

4.   Cart Functionality

5.   Checkout and Order Confirmation

6.   Admin Order Management


1. User Registration and Login

Purpose: This is the process where a new user can create an account and login to the website.

Step 1.1: User Registration

·         What happens here:

    • The user visits the registration page where they will need to fill out a form with basic information (like name, email, and password).
    • Password Hashing: The password entered is encrypted using a hashing algorithm (e.g., bcrypt) before it’s stored in the database to keep it secure.
    • Validation: The system checks if the email provided already exists in the database. If it does, the user is asked to provide a different email.
    • Once the data is validated and inserted into the database, the user will be redirected to the login page.

·         Where is the data stored: The user’s details (name, email, password, etc.) are stored in the users table in the database.

Tables involved:

  • users (id, name, email, password, role)

Step 1.2: User Login

·         What happens here:

    • Once the user has registered, they can log in using the email and password they created.
    • The system checks the entered email and password against the database records. If it’s correct, a session is created to store user data (like their user ID).
    • After successful login, the user is redirected to the homepage or dashboard.

·         Where is the data stored: The login credentials are checked against the users table.


2. Admin Login and Product Management

Purpose: The admin logs in to manage the products and the site’s content.

Step 2.1: Admin Login

  • What happens here:
    • The admin enters their credentials (email and password) to access the admin panel.
    • The system checks if the entered details are valid, and if correct, the admin is redirected to the admin dashboard.

Step 2.2: Admin Product Management

·         What happens here:

    • Once logged in, the admin can perform several actions related to products:
      • Add Products: The admin can add a new product to the store by providing product details (name, description, price, image, etc.).
      • Edit Products: The admin can edit the details of an existing product (e.g., changing the price or description).
      • Delete Products: The admin can remove a product from the store.

·         Where is the data stored: The product details (name, description, price, etc.) are stored in the products table in the database.

Tables involved:

  • products (id, name, description, price, image, category, stock)

3. Displaying Products for Users

Purpose: Users can browse the available products and view details about each product.

Step 3.1: Homepage (index.php)

  • What happens here:
    • The homepage of the website lists all available products.
    • Products are fetched from the products table and displayed with basic information (name, price, image).
    • Each product will have an “Add to Cart” button.
  • Where is the data stored: The product information is retrieved from the products table and displayed on the homepage.

4. Cart Functionality

Purpose: Users can add products to their cart and view or modify their selections.

Step 4.1: Add to Cart (add_to_cart.php)

  • What happens here:
    • When a user clicks on the "Add to Cart" button for a product, the product ID and the selected quantity are added to the cart table.
    • If the user already has the product in their cart, the quantity is updated.

Step 4.2: View Cart (cart.php)

·         What happens here:

    • The user can view the contents of their cart.
    • The cart displays all the products the user has added, including the name, quantity, and price of each product.
    • Users can modify quantities or remove products from the cart.

·         Where is the data stored: The cart information (product IDs, quantities) is stored in the cart table.

Tables involved:

  • cart (id, user_id, product_id, quantity)
  • products (id, name, price)

5. Checkout and Order Confirmation

Purpose: After reviewing their cart, users can proceed to checkout and finalize their purchase.

Step 5.1: Checkout Page (checkout.php)

  • What happens here:
    • The user is presented with a summary of their cart.
    • They will need to fill out shipping details (name, address, phone number).
    • Once confirmed, the order is placed, and the cart items are transferred to the orders and order_items tables.

Step 5.2: Order Confirmation Page

·         What happens here:

    • After placing the order, the user is shown a confirmation page that summarizes the order (product names, total price, shipping address).
    • The order is now complete, and the user’s cart is cleared.

·         Where is the data stored: The order details (user information, products, total price) are stored in the orders and order_items tables.

Tables involved:

  • orders (id, user_id, total_price, shipping_address, status)
  • order_items (id, order_id, product_id, quantity, price)

6. Admin Order Management

Purpose: The admin can view and manage the orders placed by users.

Step 6.1: Admin Order Management (admin_orders.php)

·         What happens here:

    • The admin can see a list of all orders placed by users.
    • For each order, the admin can view detailed information (user details, products ordered, total price).
    • The admin can update the status of the order (e.g., change it to "Shipped" or "Delivered").

·         Where is the data stored: The order information is stored in the orders and order_items tables.


Final Project Flow Recap:

1.   User Registration and Login:

o    User registers and logs in.

o    Admin logs in to manage products.

2.   Admin Product Management:

o    Admin can add, edit, or delete products.

3.   Displaying Products for Users:

o    Users can browse and view products on the homepage.

4.   Cart Functionality:

o    Users can add products to their cart, view their cart, and modify the cart.

5.   Checkout and Order Confirmation:

o    Users provide shipping details and place their order.

o    After checkout, the order is confirmed, and the cart is cleared.

6.   Admin Order Management:

o    Admin can view and manage user orders, updating their status as needed.


/ecommerce-project

├── /assets                # Static files (images, styles, scripts)

│   ├── /css

│   ├── /images

│   └── /js

├── /includes             # Common header, footer, sidebar, and other shared components

│   ├── header.php

│   ├── footer.php

│   ├── sidebar.php

│   └── db.php            # Database connection

├── /user                  # User Panel-related files

│   ├── register.php       # User registration page

│   ├── login.php          # User login page

│   ├── authenticate.php   # Handling login and registration logic

│   ├── index.php          # Homepage displaying all products

│   ├── product.php        # Detailed product view page

│   ├── cart.php           # Cart page showing products added to the cart

│   ├── add_to_cart.php    # Adding products to cart

│   ├── checkout.php       # Checkout page where user provides shipping info

│   ├── order_confirmation.php # Page showing order confirmation after checkout

│   ├── user_dashboard.php # Dashboard for logged-in users (can show order history, etc.)

│   └── logout.php         # User logout script

├── /admin                 # Admin Panel-related files

│   ├── admin_login.php    # Admin login page

│   ├── admin_dashboard.php # Admin dashboard page

│   ├── add_product.php    # Admin page to add new products

│   ├── edit_product.php   # Admin page to edit existing products

│   ├── delete_product.php # Admin page to delete products

│   ├── admin_orders.php   # Admin page to view and manage orders

│   └── admin_logout.php   # Admin logout script

├── /models                # Database logic models

│   ├── Product.php        # Product-related DB logic

│   ├── User.php           # User-related DB logic

│   ├── Cart.php           # Cart-related DB logic

│   └── Order.php          # Order-related DB logic

└── index.php              # Landing page or homepage for users

Flow of the project

User Flow and Admin Flow:


1. Landing Page (index.php)

For Users:

  • The first page users see when they visit the site.
  • Displays a list of all available products (from the database).
  • Users can view product details or add them to the cart from this page.

Key actions on index.php:

  • Display all products from the products table in a grid or list format.
  • Provide links to the product detail page and the cart.

2. User Registration (register.php)

For Users:

  • New users who want to create an account can visit the registration page.
  • User fills out a registration form with fields such as name, email, password, etc.

Key actions on register.php:

  • Display registration form.
  • User submits the form, which is processed by authenticate.php.

Backend (authenticate.php - Registration):

  • The data is validated (e.g., email format, password length).
  • If valid, the user is inserted into the users table.
  • On success, the user is redirected to login.php.

3. User Login (login.php)

For Users:

  • If a user already has an account, they visit the login page to authenticate.

Key actions on login.php:

  • Display a login form with fields for email and password.

Backend (authenticate.php - Login):

  • Validate the entered email and password against the users table.
  • If authentication is successful, start a session and store the user ID.
  • Redirect the user to the homepage (index.php) or user dashboard (user_dashboard.php).

4. Product View (product.php)

For Users:

  • Clicking on a product from the homepage takes the user to a detailed product page.
  • Users can see more details (like price, description, quantity) of a specific product.

Key actions on product.php:

  • Display details of the selected product.
  • Provide an "Add to Cart" button.

5. Add Product to Cart (add_to_cart.php)

For Users:

  • When a user clicks "Add to Cart" from the product page, the product is added to their cart.

Backend (add_to_cart.php):

  • The script adds the product ID and quantity to the cart table, which associates a user with the product they want to buy.

6. View Cart (cart.php)

For Users:

  • Users can view all the products they've added to their cart on the cart page.

Key actions on cart.php:

  • Display the items currently in the cart (retrieved from the cart table).
  • Show options to increase/decrease product quantities or remove items from the cart.
  • Display the total price.
  • Provide a checkout button.

7. Checkout (checkout.php)

For Users:

  • After reviewing their cart, users proceed to checkout to complete the purchase.

Key actions on checkout.php:

  • Collect shipping information (address, contact details).
  • Provide payment options (e.g., PayPal, Stripe, Cash on Delivery).
  • Display the order summary with products, prices, and total cost.

Backend (checkout.php):

  • Save the order details into the orders table.
  • Include the shipping details, payment method, and the items purchased in the order_items table.
  • After successful checkout, the user is redirected to order_confirmation.php.

8. Order Confirmation (order_confirmation.php)

For Users:

  • After the checkout is completed, the user is shown an order confirmation page.
  • The confirmation page thanks the user and provides an order summary (order ID, product details, total cost).

9. User Dashboard (user_dashboard.php)

For Users:

  • Users who are logged in can access their personal dashboard, where they can view past orders, profile details, and other information.

Key actions on user_dashboard.php:

  • Display user’s past orders (retrieved from the orders and order_items tables).
  • Provide a link to update user profile or log out.

Admin Flow:


1. Admin Login (admin_login.php)

For Admin:

  • Admin logs into the back-end system to manage products and orders.

Key actions on admin_login.php:

  • Display the admin login form (username/email and password).
  • Submit the form to admin_login_check.php to authenticate.

Backend (admin_login_check.php):

  • Validate admin credentials (check the admin table).
  • If authenticated, redirect to admin_dashboard.php.

2. Admin Dashboard (admin_dashboard.php)

For Admin:

  • The admin is taken to the dashboard where they can view options to manage products, orders, and view customer details.

Key actions on admin_dashboard.php:

  • Display options to manage products (add, edit, delete).
  • Display options to view and manage orders.

3. Manage Products:

a. Add Product (add_product.php)

  • Admin can add new products to the website.

Key actions on add_product.php:

  • Admin submits product details (name, description, price, quantity, etc.).
  • Product data is inserted into the products table.

b. Edit Product (edit_product.php)

  • Admin can edit product details such as price, description, quantity, etc.

Key actions on edit_product.php:

  • Admin selects a product to edit.
  • The existing product details are fetched and shown in a form.
  • Upon editing, the product is updated in the products table.

c. Delete Product (delete_product.php)

  • Admin can delete a product from the website.

Key actions on delete_product.php:

  • Admin selects a product to delete.
  • The product is deleted from the products table.

4. Manage Orders (admin_orders.php)

For Admin:

  • The admin can view all orders placed by users, including order details and customer information.

Key actions on admin_orders.php:

  • Admin can view orders from the orders table.
  • Admin can view details of each order, including the products purchased, shipping address, and payment status.

5. Admin Logout (admin_logout.php)

For Admin:

  • Admin logs out from the system.

Key actions on admin_logout.php:

  • Destroy the admin session and redirect to admin_login.php.

Summary of Flow:

User Flow:

1.   Visit the landing page (index.php) and view products.

2.   Register on register.php (if new) or log in on login.php.

3.   Browse products and add them to the cart.

4.   Go to the cart (cart.php) to review products and proceed to checkout.

5.   Enter shipping details and make payment on checkout.php.

6.   View order confirmation on order_confirmation.php.

7.   View past orders and update profile in the user_dashboard.php.

Admin Flow:

1.   Log in to the admin panel on admin_login.php.

2.   Access the dashboard (admin_dashboard.php) to manage products and orders.

3.   Add, edit, or delete products on add_product.php, edit_product.php, and delete_product.php.

4.   View and manage orders on admin_orders.php.

5.   Log out from the admin panel on admin_logout.php.

 the flow and interaction between productsuserscart, and orders

1. Product Management (Admin)

The Product is a key entity in an e-commerce website. Admins need to manage products (add, edit, delete) through the admin panel.

Product Table Structure (products)

CREATE TABLE products (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  description TEXT,
  price DECIMAL(10, 2) NOT NULL,
  quantity INT NOT NULL,
  image VARCHAR(255),  -- Path to product image
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Product Management Flow:

  • Add Product: Admin adds new products to the system via the add_product.php page, where they can input product details such as name, description, price, quantity, and image. This data is saved in the products table.
  • Edit Product: Admin can edit product details through edit_product.php, fetching data from the products table and allowing updates.
  • Delete Product: Admin can delete a product from the website via delete_product.php, which removes the product from the products table.

2. User Registration & Management

Users need to create an account to make purchases. After logging in, users can browse products, add them to their cart, and proceed to checkout.

User Table Structure (users)

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL,
  password VARCHAR(255) NOT NULL,
  role ENUM('user', 'admin') DEFAULT 'user',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

User Management Flow:

  • Register User: A new user registers via register.php by filling in their details (name, email, password). The data is validated and inserted into the users table. The password is hashed before being stored.
  • Login User: A registered user can log in through login.php. The email and password are checked against the users table to authenticate the user. If valid, the user is logged in, and a session is created.
  • User Dashboard: Once logged in, the user is redirected to the user_dashboard.php, where they can view their past orders and profile.

3. Cart Management (User)

The cart is a temporary collection of products a user intends to purchase. It allows users to review and modify the contents before proceeding to checkout.

Cart Table Structure (cart)

CREATE TABLE cart (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  product_id INT NOT NULL,
  quantity INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id),
  FOREIGN KEY (product_id) REFERENCES products(id)
);

Cart Management Flow:

  • Add to Cart: When a user clicks "Add to Cart" from the product.php page, the product is added to the cart table with the product_id, user_id, and quantity.
  • View Cart: The user can view all items in their cart by navigating to cart.php. This page retrieves the items from the cart table and displays the product name, quantity, and total price.
  • Modify Cart: Users can modify the cart (change quantity or remove products) by interacting with options on cart.php. For example, updating the quantity will update the quantity field in the cart table, and removing a product will delete the corresponding entry from the cart table.

4. Order Management (User and Admin)

Once the user has reviewed their cart and is ready to purchase, they proceed to checkout. After completing the checkout, the order is saved, and the user is shown a confirmation.

Order Table Structure (orders)

CREATE TABLE orders (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  total_price DECIMAL(10, 2) NOT NULL,
  shipping_address VARCHAR(255) NOT NULL,
  payment_status ENUM('pending', 'paid', 'failed') DEFAULT 'pending',
  order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id)
);

Order Item Table Structure (order_items)

CREATE TABLE order_items (
  id INT AUTO_INCREMENT PRIMARY KEY,
  order_id INT NOT NULL,
  product_id INT NOT NULL,
  quantity INT NOT NULL,
  price DECIMAL(10, 2) NOT NULL,
  FOREIGN KEY (order_id) REFERENCES orders(id),
  FOREIGN KEY (product_id) REFERENCES products(id)
);

Order Management Flow:

·         Checkout: When the user clicks on "Checkout" from the cart, they enter shipping details, choose a payment method, and review the order summary. After confirming the details, the order is inserted into the orders table, and the items in the cart are inserted into the order_items table.

    • The orders table holds general order information (total price, shipping address, and payment status).
    • The order_items table stores detailed information about the products ordered (product_id, quantity, and price).

·         Order Confirmation: After completing the checkout, the user is shown an order confirmation page (order_confirmation.php) where they can see the order summary.

·         Admin Order Management: Admin can view all orders placed by users on admin_orders.php. This page shows order details, including the products ordered, user information, and payment status. Admins can manage order status (e.g., mark an order as shipped or delivered).


Final Flow Between User, Product, Cart, and Order

1.   User Registration/Login:

o    The user registers or logs in.

o    On successful login, the user is directed to the homepage (index.php) or the user dashboard (user_dashboard.php).

2.   Product Browsing:

o    The user browses products on index.php or views detailed product pages (product.php).

o    The user can click "Add to Cart" to add products to their cart.

3.   Cart Management:

o    Products added to the cart are stored in the cart table.

o    The user can view and modify the cart on cart.php.

4.   Checkout and Order Creation:

o    When ready to purchase, the user proceeds to checkout on checkout.php.

o    The order is saved in the orders table, and each item in the cart is moved to the order_items table.

5.   Order Confirmation:

o    After successful checkout, the user is shown a confirmation page (order_confirmation.php), and the order details are stored in the database.

6.   Admin Management:

o    Admins can view and manage orders through the admin_orders.php page.

o    Admins also have the ability to add, edit, and delete products via the admin dashboard.


Summary

  • Products: Managed by the admin and stored in the products table.
  • Users: Registered users can log in, view products, add items to their cart, and place orders. User data is stored in the users table.
  • Cart: Holds the products the user wants to buy before they proceed to checkout. Cart data is stored in the cart table.
  • Orders: Once the user completes the checkout process, the order is stored in the orders table, and individual products in the order are stored in the order_items table.

Summary of Steps

1.   Create the database and tables.

2.   Create the registration and login pages (register.php, login.php).

3.   Set up user authentication logic (authenticate.php).

4.   Create the landing page (index.php) to display products.

5.   Set up the admin panel for managing products (add_product.php, edit_product.php, delete_product.php).

6.   Create cart and checkout functionality (add_to_cart.php, cart.php, checkout.php).

7.   Create order confirmation page (order_confirmation.php).

8.   Set up order management for the admin (admin_orders.php).

 


Source Code :


Step 1: Set up the Database

1.   Create the database (ecommerce_db):

o    Use phpMyAdmin or MySQL commands to create a new database.

o    Create the necessary tables: users, products, orders, and cart.

SQL queries:

CREATE DATABASE ecommerce_db;

USE ecommerce_db;

 

-- Users table

CREATE TABLE users (

    id INT(11) AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) NOT NULL,

    email VARCHAR(255) UNIQUE NOT NULL,

    password VARCHAR(255) NOT NULL,

    role ENUM('user', 'admin') DEFAULT 'user',

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);

 

-- Products table

CREATE TABLE products (

    id INT(11) AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) NOT NULL,

    description TEXT,

    price DECIMAL(10,2) NOT NULL,

    image VARCHAR(255),

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);

 

-- Orders table

CREATE TABLE orders (

    id INT(11) AUTO_INCREMENT PRIMARY KEY,

    user_id INT(11),

    total DECIMAL(10,2) NOT NULL,

    status ENUM('pending', 'completed', 'cancelled') DEFAULT 'pending',

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id)

);

 

-- Cart table

CREATE TABLE cart (

    id INT(11) AUTO_INCREMENT PRIMARY KEY,

    user_id INT(11),

    product_id INT(11),

    quantity INT(11) DEFAULT 1,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id),

    FOREIGN KEY (product_id) REFERENCES products(id)

);


Step 2: Set up Database Connection

1.   Create config/db.php to handle the connection to the MySQL database:

<?php

// config/db.php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "ecommerce_db";

 

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

 

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

?>


Step 3: User Registration

1.   Create register.php for user registration:

o    Include a form for entering user details (name, email, password).

o    Insert data into the users table.

<?php

// register.php

require_once 'config/db.php';

 

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $name = $_POST['name'];

    $email = $_POST['email'];

    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

 

    // Insert user into the database

    $sql = "INSERT INTO users (name, email, password) VALUES ('$name', '$email', '$password')";

    if (mysqli_query($conn, $sql)) {

        echo "Registration successful!";

    } else {

        echo "Error: " . mysqli_error($conn);

    }

}

?>

2.   Create the login.php for user login functionality:

o    Authenticate the user based on the email and password.

<?php

// login.php

require_once 'config/db.php';

 

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $email = $_POST['email'];

    $password = $_POST['password'];

 

    // Check if user exists and verify password

    $sql = "SELECT * FROM users WHERE email = '$email'";

    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {

        $user = mysqli_fetch_assoc($result);

        if (password_verify($password, $user['password'])) {

            // Login successful

            session_start();

            $_SESSION['user_id'] = $user['id'];

            $_SESSION['user_name'] = $user['name'];

            header("Location: index.php"); // Redirect to home page

        } else {

            echo "Invalid credentials!";

        }

    } else {

        echo "User not found!";

    }

}

?>


Step 4: Create the Landing Page (index.php)

1.   Create index.php to display products and handle user login/register links.

// index.php

<?php

require_once 'config/db.php';

 

// Fetch all products from the database

$sql = "SELECT * FROM products";

$result = mysqli_query($conn, $sql);

?>

 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Shop</title>

</head>

<body>

 

<?php if (!isset($_SESSION['user_id'])): ?>

    <p><a href="login.php">Login</a> | <a href="register.php">Register</a></p>

<?php else: ?>

    <p>Welcome, <?php echo $_SESSION['user_name']; ?>!</p>

<?php endif; ?>

 

<h2>Our Products</h2>

<div>

    <?php while ($product = mysqli_fetch_assoc($result)): ?>

        <div>

            <h3><?php echo $product['name']; ?></h3>

            <p><?php echo $product['description']; ?></p>

            <p>Price: $<?php echo $product['price']; ?></p>

            <a href="add_to_cart.php?product_id=<?php echo $product['id']; ?>">Add to Cart</a>

        </div>

    <?php endwhile; ?>

</div>

 

</body>

</html>


Step 5: Admin Panel Setup

1.   Create admin_login.php for admin login:

o    Admin login functionality using email and password.

2.   Create admin_dashboard.php for the admin dashboard:

o    Display products, options to add, edit, and delete products.

3.   Create add_product.php for adding products to the store:

o    Admin can add product details (name, description, price, image).

// add_product.php

require_once 'config/db.php';

 

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $name = $_POST['name'];

    $description = $_POST['description'];

    $price = $_POST['price'];

    $image = $_POST['image'];

 

    // Insert new product into products table

    $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);

    }

}

?> 

<form method="POST">

    <input type="text" name="name" placeholder="Product Name">

    <textarea name="description" placeholder="Product Description"></textarea>

    <input type="number" name="price" placeholder="Price">

    <input type="text" name="image" placeholder="Product Image URL">

    <button type="submit">Add Product</button>

</form>

4.   Create edit_product.php for editing existing products.

5.   Create delete_product.php for deleting products.


Step 6: Cart and Checkout

1.   Create add_to_cart.php to add products to the cart.

// add_to_cart.php

require_once 'config/db.php'; 

$product_id = $_GET['product_id'];

$user_id = $_SESSION['user_id'];

 

// Check if product already exists in the cart

$sql = "SELECT * FROM cart WHERE user_id = '$user_id' AND product_id = '$product_id'";

$result = mysqli_query($conn, $sql);

 

if (mysqli_num_rows($result) > 0) {

    // Update quantity

    $sql = "UPDATE cart SET quantity = quantity + 1 WHERE user_id = '$user_id' AND product_id = '$product_id'";

} else {

    // Add new product to cart

    $sql = "INSERT INTO cart (user_id, product_id, quantity) VALUES ('$user_id', '$product_id', 1)";

}

 

if (mysqli_query($conn, $sql)) {

    header('Location: cart.php');

}

2.   Create cart.php to display the cart:

o    Show all products in the cart with quantity and total price.

3.   Create checkout.php to handle checkout.

4.   Create order_confirmation.php to show the confirmation message.


Step 7: Admin Order Management

1.   Create admin_orders.php to display orders with their status.

2.   Create update_order_status.php to change the status of orders.


 




 



Post a Comment

0Comments

Post a Comment (0)