"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Wednesday, September 18, 2024

E-Commerce Website using PHP and MYSQL (Using query() method)

 E-Commerce Website using PHP and MYSQL (Using query() method)

Here is a basic project structure for an e-commerce website built using PHP, MySQL, and Bootstrap. The project structure includes the necessary files and directories for user and admin functionalities, product management, user authentication, cart management, and purchase flow.

Project Structure

/ecommerce-website

── /admin                    # Admin panel for managing the website

   ── /css                  # Admin-specific styles (use Bootstrap)

   ── /js                   # Admin-specific JavaScript (if needed)

   ── /images               # Admin panel images or icons

   ── /partials             # Includes header, sidebar, footer

      ── header.php        # Admin header

      ── sidebar.php       # Admin sidebar

      └── footer.php        # Admin footer

   ── add_product.php       # Add new products (Admin)

   ── edit_product.php      # Edit existing products (Admin)

   ── delete_product.php    # Delete product (Admin)

   ── view_orders.php       # View all orders (Admin)

   ── view_users.php        # Manage users (Admin)

   └── dashboard.php         # Admin dashboard

── /assets                    # Common assets (styles, scripts, images)

   ── /css                  # Common CSS (use Bootstrap)

      └── style.css         # Custom styles

   ── /js                   # Common JavaScript

   └── /images               # Website images

── /includes                  # Common includes for header, footer, and db connection

   ── header.php            # Front-end header (includes navigation bar)

   ── footer.php            # Front-end footer

   └── db_connect.php        # Database connection file

── /user                      # User-related files

   ── /cart                 # Cart management

      ── add_to_cart.php   # Add item to cart

      ── remove_from_cart.php # Remove item from cart

      ── view_cart.php     # View cart

   └── /auth                 # User authentication

       ── login.php         # User login

       ── register.php      # User registration

       ── logout.php        # User logout

   ── /profile              # User profile management

       ── view_profile.php  # View profile

       ── edit_profile.php  # Edit profile

   └── /orders               # User orders

       ── view_orders.php   # View user's orders

       ── checkout.php      # Checkout process

       └── place_order.php   # Place order

── /products                  # Product catalog and management

   ── product_list.php       # List all products for users

   ── product_details.php    # Display detailed view of a product

   ── search.php             # Search products

── /uploads                   # Folder for storing product images and user-uploaded files

── index.php                  # Homepage

── about.php                  # About page

── contact.php                # Contact page

── process_contact.php        # Process contact form submissions

└── README.md                  # Project documentation

Explanation of Key Components

1.     Admin Panel (/admin):

o    Admin can manage products (add_product.php, edit_product.php, delete_product.php), view orders (view_orders.php), and manage users (view_users.php).

o    Includes partial files for reusability (header.php, footer.php, sidebar.php).

2.     Assets (/assets):

o    Contains common resources like styles (style.css), scripts, and images shared across both admin and user sections. Use Bootstrap for styling.

3.     Includes (/includes):

o    header.php and footer.php for consistent navigation and footer across pages.

o    db_connect.php manages the connection to the MySQL database.

4.     User (/user):

o    Handles user authentication (login.php, register.php, logout.php).

o    User profile management and viewing orders.

o    Cart functionality (add_to_cart.php, view_cart.php, remove_from_cart.php) and the checkout process.

5.     Products (/products):

o    product_list.php: Displays all available products.

o    product_details.php: Shows details of a specific product.

o    search.php: Product search functionality.

6.     Uploads (/uploads):

o    Stores product images or other media.

7.     Home Page & Static Pages:

o    index.php: Front-facing homepage.

o    about.php, contact.php: Informational pages with a contact form.

Features Included

  • User Authentication: Login, registration, and logout.
  • Product Management: Add, edit, and delete products (admin).
  • Cart System: Users can add products to the cart, view their cart, and proceed to checkout.
  • Order Management: Users can place orders and view their order history. Admin can view all orders.
  • Admin Panel: Separate section for admin to manage products and view users/orders.
  • Responsive Design: Bootstrap ensures the website is mobile-friendly and responsive.

 

DATABASE SCHEMA
Here is the SQL query to create a database for your e-commerce website and create all the necessary tables such as users, products, categories, cart, orders, and order_items. Each table will include relevant fields for the ecommerce website's functionalities.

1. Database Creation

CREATE DATABASE ecommerce;

USE ecommerce;

2. Table Creation

users Table (For storing user information)

CREATE TABLE users (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) NOT NULL,

    email VARCHAR(255) NOT NULL UNIQUE,

    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

);

categories Table (For storing product categories)

CREATE TABLE categories (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);

products Table (For storing product details)

CREATE TABLE products (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) NOT NULL,

    price DECIMAL(10, 2) NOT NULL,

    description TEXT,

    category_id INT,

    image VARCHAR(255),

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL

);

cart Table (For storing items in the user's cart)

CREATE TABLE cart (

    id INT AUTO_INCREMENT PRIMARY KEY,

    user_id INT,

    product_id INT,

    quantity INT NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,

    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE

);

orders Table (For storing order details)

CREATE TABLE orders (

    id INT AUTO_INCREMENT PRIMARY KEY,

    user_id INT,

    total DECIMAL(10, 2) NOT NULL,

    status ENUM('pending', 'shipped', 'delivered', '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) ON DELETE CASCADE

);

order_items Table (For storing each product in an order)

CREATE TABLE order_items (

    id INT AUTO_INCREMENT PRIMARY KEY,

    order_id INT,

    product_id INT,

    quantity INT NOT NULL,

    price DECIMAL(10, 2) NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,

    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE

);


SQL Script Breakdown:

1.     users Table: Stores user registration details with a role that can either be user or admin.

2.     categories Table: Stores different product categories.

3.     products Table: Contains the product details with a foreign key (category_id) referring to the categories table.

4.     cart Table: Holds the user’s shopping cart items with foreign keys linking the users and products tables.

5.     orders Table: Stores order details such as the total price and status of the order.

6.     order_items Table: Stores individual product details within an order, linking orders and products.

Entity-Relationship (ER) diagram

An Entity-Relationship (ER) diagram visually represents the structure of a database, including the tables (entities) and their relationships.

ER Diagram Description

Entities and Attributes

1.     User

o    id (Primary Key)

o    name

o    email

o    password

o    role (User/Admin)

o    created_at

o    updated_at

2.     Category

o    id (Primary Key)

o    name

o    created_at

o    updated_at

3.     Product

o    id (Primary Key)

o    name

o    price

o    description

o    category_id (Foreign Key)

o    image

o    created_at

o    updated_at

4.     Cart

o    id (Primary Key)

o    user_id (Foreign Key)

o    product_id (Foreign Key)

o    quantity

o    created_at

5.     Order

o    id (Primary Key)

o    user_id (Foreign Key)

o    total

o    status (Pending/Shipped/Delivered/Cancelled)

o    created_at

o    updated_at

6.     Order_Item

o    id (Primary Key)

o    order_id (Foreign Key)

o    product_id (Foreign Key)

o    quantity

o    price

o    created_at

Relationships

  • User to Cart: One-to-Many
    • A user can have multiple items in their cart.
    • user_id in Cart is a foreign key that references id in User.
  • Product to Cart: One-to-Many
    • A product can appear in multiple carts.
    • product_id in Cart is a foreign key that references id in Product.
  • User to Order: One-to-Many
    • A user can place multiple orders.
    • user_id in Order is a foreign key that references id in User.
  • Order to Order_Item: One-to-Many
    • An order can contain multiple order items.
    • order_id in Order_Item is a foreign key that references id in Order.
  • Product to Order_Item: One-to-Many
    • A product can appear in multiple order items.
    • product_id in Order_Item is a foreign key that references id in Product.
  • Category to Product: One-to-Many
    • A category can have multiple products.
    • category_id in Product is a foreign key that references id in Category.

ER Diagram Representation

  +---------+          +---------+          +--------+

  |  User   |          | Category|          |Product |

  +---------+          +---------+          +--------+

  | id (PK) |<-------->| id (PK) |<-------->| id (PK)|

  | name    |          | name    |          | name   |

  | email   |          | created_at |       | price  |

  | password|          | updated_at |       | description |

  | role    |          +---------+          | category_id (FK) |

  | created_at |                               | created_at  |

  | updated_at |                               | updated_at  |

  +---------+                                 +--------+

       |                                           |

       |                                           |

       |                                           |

       |                                           |

  +---------+          +---------+                 +---------+

  |  Cart   |          |  Order  |                 | Order_Item |

  +---------+          +---------+                 +---------+

  | id (PK) |          | id (PK) |                 | id (PK) |

  | user_id (FK)|<---->| user_id (FK) |<----->| order_id (FK) |

  | product_id (FK)|   | total   |                 | product_id (FK) |

  | quantity |          | status  |                 | quantity |

  | created_at |        | created_at |              | price   |

  +---------+          | updated_at |             | created_at |

                       +---------+                +---------+

Relationships Summary

  • User has a Cart and Order.
  • Product is part of a Cart and Order_Item.
  • Order consists of multiple Order_Item entries.
  • Product belongs to a Category.

You can use ER diagram tools like Lucidchart, draw.io, or MySQL Workbench to create a visual representation of this diagram.

 

Data Flow Diagram (DFD)

A Data Flow Diagram (DFD) represents the flow of data within a system. It visualizes how data moves between processes, data stores, and external entities. Here's a detailed DFD for the e-commerce website project.

Level 0 DFD (Context Diagram)

This diagram provides a high-level overview of the entire system.

External Entities:

1.     User: Interacts with the system to browse products, manage the cart, place orders, and view orders.

2.     Admin: Manages products, categories, and views orders.

Process:

1.     E-Commerce System: The main system that handles user interactions and admin functions.

Data Flows:

  • User to E-Commerce System: Requests for browsing products, managing the cart, and placing orders.
  • E-Commerce System to User: Provides product information, cart updates, and order confirmations.
  • Admin to E-Commerce System: Requests for product and category management, and viewing orders.
  • E-Commerce System to Admin: Provides product, category, and order information.

Level 1 DFD

This level breaks down the E-Commerce System into more detailed processes.

Processes:

1.     User Authentication: Handles user registration, login, and profile management.

2.     Product Management: Allows admins to add, edit, or delete products and manage categories.

3.     Cart Management: Manages adding items to the cart, updating quantities, and removing items.

4.     Order Processing: Handles placing orders, processing payments, and generating order confirmations.

5.     Order Management: Manages and views orders for admin purposes.

Data Stores:

1.     User Database: Stores user information, credentials, and roles.

2.     Product Database: Stores product details, categories, and images.

3.     Cart Database: Stores cart items for users.

4.     Order Database: Stores orders and order items.

Data Flows:

  • User Authentication:
    • User to User Database: Registration and login requests.
    • User Database to User: Authentication results.
  • Product Management:
    • Admin to Product Database: Requests to add, edit, or delete products and categories.
    • Product Database to Admin: Confirmation of changes and updated product information.
  • Cart Management:
    • User to Cart Database: Add or update cart items.
    • Cart Database to User: Cart updates and item details.
  • Order Processing:
    • User to Order Database: Order placement requests.
    • Order Database to User: Order confirmations and status updates.
  • Order Management:
    • Admin to Order Database: Requests to view and manage orders.
    • Order Database to Admin: Order details and status updates.

Level 2 DFD (Detailed View)

1. User Authentication Process

  • User Registration:
    • User to User Database: Registration data (name, email, password).
    • User Database to User: Registration confirmation.
  • User Login:
    • User to User Database: Login credentials (email, password).
    • User Database to User: Authentication results (success/failure).
  • Profile Management:
    • User to User Database: Profile update requests.
    • User Database to User: Updated profile information.

2. Product Management Process

  • Add/Edit Product:
    • Admin to Product Database: Product details (name, price, description, image).
    • Product Database to Admin: Confirmation of product addition or update.
  • Delete Product:
    • Admin to Product Database: Product ID for deletion.
    • Product Database to Admin: Confirmation of product deletion.

3. Cart Management Process

  • Add/Update Cart Item:
    • User to Cart Database: Product ID, quantity.
    • Cart Database to User: Updated cart details.
  • Remove Cart Item:
    • User to Cart Database: Product ID for removal.
    • Cart Database to User: Updated cart details.

4. Order Processing Process

  • Place Order:
    • User to Order Database: Order details (cart items, total, user ID).
    • Order Database to User: Order confirmation.
  • Process Payment:
    • User to Payment Gateway: Payment information.
    • Payment Gateway to Order Database: Payment confirmation.

5. Order Management Process

  • View Orders:
    • Admin to Order Database: Request to view orders.
    • Order Database to Admin: List of orders with details.

DFD Summary

Level 0 DFD:

  • Shows the interaction between Users, Admins, and the E-Commerce System.

Level 1 DFD:

  • Breaks down the E-Commerce System into User Authentication, Product Management, Cart Management, Order Processing, and Order Management processes.

Level 2 DFD:

  • Details the sub-processes within each of the main processes.

Diagram Visualization

Creating a visual DFD can be done using tools like Lucidchart, draw.io, or Microsoft Visio.

Level 0 DFD:

  +---------------------+

  |                     |

  |  E-Commerce System  |

  |                     |

  +---------+-----------+

            |

   +--------+----------+

   |                   |

+--v--+              +--v--+

|User |              |Admin|

+-----+              +-----+

 

Level 1 DFD:

+-------------------+

| User Authentication|

+-------------------+

        |

+-------+-------+

| Cart Management|

+---------------+

        |

+-------+-------+

| Order Processing|

+---------------+

        |

+-------+-------+

| Order Management|

+---------------+

        |

+-------+-------+

| Product Management|

+---------------+

 

 

Detailed Level 2 DFD

1. User Authentication Process

  • User Registration:
    • Input: User provides registration details (name, email, password).
    • Process:
      • Validate input data.
      • Hash the password for security.
      • Store user details in the users table.
    • Output: Registration confirmation to the user.

Data Flow:

    • User to User Authentication Process: Registration data.
    • User Authentication Process to User Database: Store user information.
    • User Database to User Authentication Process: Confirmation of registration.
    • User Authentication Process to User: Registration confirmation.
  • User Login:
    • Input: User provides email and password.
    • Process:
      • Validate login credentials.
      • Check credentials against the users table.
      • Generate session token or cookie.
    • Output: Login result (success/failure) to the user.

Data Flow:

    • User to User Authentication Process: Login credentials.
    • User Authentication Process to User Database: Validate credentials.
    • User Database to User Authentication Process: Authentication result.
    • User Authentication Process to User: Login result.
  • Profile Management:
    • Input: User provides updated profile information.
    • Process:
      • Validate and update profile data in the users table.
    • Output: Updated profile information to the user.

Data Flow:

    • User to User Authentication Process: Profile update request.
    • User Authentication Process to User Database: Update profile information.
    • User Database to User Authentication Process: Confirmation of update.
    • User Authentication Process to User: Updated profile information.

2. Product Management Process

  • Add/Edit Product:
    • Input: Admin provides product details (name, price, description, category, image).
    • Process:
      • Validate input data.
      • Insert or update product information in the products table.
    • Output: Confirmation of product addition or update to the admin.

Data Flow:

    • Admin to Product Management Process: Product details.
    • Product Management Process to Product Database: Add or update product information.
    • Product Database to Product Management Process: Confirmation of addition or update.
    • Product Management Process to Admin: Confirmation message.
  • Delete Product:
    • Input: Admin provides product ID for deletion.
    • Process:
      • Validate product ID.
      • Remove product from the products table.
    • Output: Confirmation of product deletion to the admin.

Data Flow:

    • Admin to Product Management Process: Product ID for deletion.
    • Product Management Process to Product Database: Delete product.
    • Product Database to Product Management Process: Confirmation of deletion.
    • Product Management Process to Admin: Confirmation message.

3. Cart Management Process

  • Add/Update Cart Item:
    • Input: User provides product ID and quantity.
    • Process:
      • Validate input data.
      • Add or update cart items in the cart table.
    • Output: Updated cart details to the user.

Data Flow:

    • User to Cart Management Process: Cart item details.
    • Cart Management Process to Cart Database: Add or update cart items.
    • Cart Database to Cart Management Process: Updated cart information.
    • Cart Management Process to User: Updated cart details.
  • Remove Cart Item:
    • Input: User provides product ID for removal.
    • Process:
      • Validate product ID.
      • Remove item from the cart table.
    • Output: Updated cart details to the user.

Data Flow:

    • User to Cart Management Process: Product ID for removal.
    • Cart Management Process to Cart Database: Remove cart item.
    • Cart Database to Cart Management Process: Updated cart information.
    • Cart Management Process to User: Updated cart details.

4. Order Processing Process

  • Place Order:
    • Input: User submits order details (cart items, total amount).
    • Process:
      • Validate order data.
      • Store order details in the orders table.
      • Store order items in the order_items table.
    • Output: Order confirmation to the user.

Data Flow:

    • User to Order Processing Process: Order details.
    • Order Processing Process to Order Database: Store order information.
    • Order Processing Process to Order Items Database: Store order items.
    • Order Database to Order Processing Process: Order confirmation.
    • Order Processing Process to User: Order confirmation.
  • Process Payment:
    • Input: User provides payment information.
    • Process:
      • Validate payment details.
      • Process payment through a payment gateway.
      • Update order status in the orders table.
    • Output: Payment confirmation to the user.

Data Flow:

    • User to Order Processing Process: Payment information.
    • Order Processing Process to Payment Gateway: Process payment.
    • Payment Gateway to Order Database: Payment confirmation.
    • Order Database to Order Processing Process: Updated order status.
    • Order Processing Process to User: Payment confirmation.

5. Order Management Process

  • View Orders:
    • Input: Admin requests to view orders.
    • Process:
      • Retrieve orders from the orders table.
      • Provide order details to the admin.
    • Output: List of orders with details to the admin.

Data Flow:

    • Admin to Order Management Process: Request to view orders.
    • Order Management Process to Order Database: Retrieve order details.
    • Order Database to Order Management Process: Order information.
    • Order Management Process to Admin: List of orders.

Visual Representation

For a visual representation of this DFD, you can use tools like Lucidchart, draw.io, or Microsoft Visio.

Level 2 DFD for User Authentication:

 

  +-----------------+

  |  User           |

  +--------+--------+

           |

           v

  +-----------------------------+

  |  User Authentication Process|

  +-----------------------------+

    |       |          |

    v       v          v

+---+---+ +---+---+  +---+---+

| User  | | User  |  | User  |

|Registration| | Login |  | Profile|

|            | |      |  |Management|

+---+---+   +---+---+  +---+---+

    |           |          |

    v           v          v

+---+---+   +---+---+  +---+---+

| User  | | User  |  | User  |

|Database| |Database| |Database|

+--------+ +--------+ +--------+

 

Level 2 DFD for Product Management:

 

  +------------------------+

  | Product Management     |

  +------------------------+

    |         |          |

    v         v          v

+---+---+ +---+---+  +---+---+

| Add/  | | Edit/ |  | Delete|

|Edit   | |Update |  | Product|

+-------+ +-------+  +-------+

    |          |           |

    v          v           v

+---+---+ +---+---+  +---+---+

|Product| |Product| |Product|

|Database| |Database| |Database|

+--------+ +--------+ +--------+

 

Level 2 DFD for Cart Management:

 

  +-------------------+

  | Cart Management   |

  +-------------------+

    |        |        |

    v        v        v

+---+---+ +---+---+  +---+---+

| Add/  | | Update|  | Remove|

|Update | | Cart  |  | Item  |

+-------+ +-------+  +-------+

    |          |          |

    v          v          v

+---+---+ +---+---+  +---+---+

| Cart  | | Cart  | | Cart  |

|Database| |Database| |Database|

+--------+ +--------+ +--------+

 

Level 2 DFD for Order Processing:

 

  +---------------------+

  | Order Processing    |

  +---------------------+

    |          |        |

    v          v        v

+---+---+ +---+---+  +---+---+

| Place | | Process|  | Payment|

| Order | | Order  |  |        |

+-------+ +-------+  +-------+

    |           |          |

    v           v          v

+---+---+   +---+---+  +---+---+

| Order |   |Order  |  |Payment |

|Database| | Items |  |Gateway |

+--------+ +--------+ +--------+

 

Level 2 DFD for Order Management:

 

  +-------------------+

  | Order Management  |

  +-------------------+

           |

           v

  +-------------------+

  | View Orders       |

  +-------------------+

           |

           v

  +-------------------+

  | Order Database    |

  +-------------------+

This Level 2 DFD provides a detailed view of each major process and how data flows through the system.

CODE SECTION

1. /includes/db_connect.php

<?php

// Database connection

$host = 'localhost';

$user = 'root';

$pass = '';

$db_name = 'ecommerce';

$conn = mysqli_connect($host, $user, $pass, $db_name);

// Check connection

if (!$conn) {

    die("Connection failed: " . mysqli_connect_error());

}

?>


2. /admin/add_product.php

<?php

include '../includes/db_connect.php';

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

    $product_name = $_POST['product_name'];

    $price = $_POST['price'];

    $description = $_POST['description'];

    $category = $_POST['category'];

    $image = $_FILES['image']['name'];

    // Upload product image

    $target_dir = "../uploads/";

    $target_file = $target_dir . basename($image);

    move_uploaded_file($_FILES['image']['tmp_name'], $target_file);

    $query = "INSERT INTO products (name, price, description, category, image)

              VALUES ('$product_name', '$price', '$description', '$category', '$image')";

  

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

        echo "Product added successfully!";

    } else {

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

    }

}

?>

<form method="POST" enctype="multipart/form-data">

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

    <input type="text" name="price" placeholder="Price" required>

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

    <input type="text" name="category" placeholder="Category" required>

    <input type="file" name="image" required>

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

</form>


3. /admin/edit_product.php

<?php

include '../includes/db_connect.php';

$product_id = $_GET['id'];

$query = "SELECT * FROM products WHERE id = '$product_id'";

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

$product = mysqli_fetch_assoc($result);

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

    $product_name = $_POST['product_name'];

    $price = $_POST['price'];

    $description = $_POST['description'];

    $category = $_POST['category'];

    $update_query = "UPDATE products SET

                        name = '$product_name',

                        price = '$price',

                        description = '$description',

                        category = '$category'

                     WHERE id = '$product_id'";

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

        echo "Product updated successfully!";

    } else {

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

    }

}

?>

<form method="POST">

    <input type="text" name="product_name" value="<?= $product['name'] ?>" required>

    <input type="text" name="price" value="<?= $product['price'] ?>" required>

    <textarea name="description" required><?= $product['description'] ?></textarea>

    <input type="text" name="category" value="<?= $product['category'] ?>" required>

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

</form>


4. /admin/delete_product.php

<?php

include '../includes/db_connect.php';

$product_id = $_GET['id'];

$query = "DELETE FROM products WHERE id = '$product_id'";

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

    echo "Product deleted successfully!";

} else {

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

}

?>


5. /admin/view_orders.php

<?php

include '../includes/db_connect.php';

$query = "SELECT * FROM orders";

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

while ($order = mysqli_fetch_assoc($result)) {

    echo "Order ID: " . $order['id'] . " - User ID: " . $order['user_id'] . " - Total: " . $order['total'] . "<br>";

}

?>


6. /user/auth/login.php

<?php

include '../../includes/db_connect.php';

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

    $email = $_POST['email'];

    $password = $_POST['password'];

    $query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";

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

    if (mysqli_num_rows($result) > 0) {

        session_start();

        $_SESSION['user'] = mysqli_fetch_assoc($result);

        header('Location: ../profile/view_profile.php');

    } else {

        echo "Invalid login credentials!";

    }

}

?>

<form method="POST">

    <input type="email" name="email" placeholder="Email" required>

    <input type="password" name="password" placeholder="Password" required>

    <button type="submit">Login</button>

</form>


7. /user/auth/register.php

<?php

// Database connection settings

$servername = "localhost";

$username = "root"; // Update with your database username

$password = ""; // Update with your database password

$database = "ecommerce"; // Update with your database name

 

// Create connection

$conn = mysql_connect($servername, $username, $password);

 

// Check connection

if (!$conn) {

    die("Connection failed: " . mysql_error());

}

 

// Select the database

mysql_select_db($database, $conn);

 

// Function to sanitize input data

function sanitize_input($data) {

    global $conn;

    return mysql_real_escape_string(trim($data));

}

 

// Check if form is submitted

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

    // Retrieve and sanitize user inputs

    $name = sanitize_input($_POST['name']);

    $email = sanitize_input($_POST['email']);

    $password = sanitize_input($_POST['password']);

    $confirm_password = sanitize_input($_POST['confirm_password']);

    $role = sanitize_input($_POST['role']);

 

    // Validate inputs

    if (empty($name) || empty($email) || empty($password) || empty($confirm_password) || empty($role)) {

        echo "All fields are required.";

    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        echo "Invalid email format.";

    } elseif ($password !== $confirm_password) {

        echo "Passwords do not match.";

    } else {

        // Hash the password

        $hashed_password = md5($password); // Using md5 for demonstration, use password_hash() if possible

 

        // Prepare SQL query

        $query = "INSERT INTO users (name, email, password, role) VALUES ('$name', '$email', '$hashed_password', '$role')";

 

        // Execute the query

        if (mysql_query($query, $conn)) {

            echo "Registration successful!";

        } else {

            echo "Error: " . mysql_error();

        }

    }

}

 

// Close connection

mysql_close($conn);

?>

 

<!-- HTML form for registration -->

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>User Registration</title>

    <link rel="stylesheet" href="styles.css"> <!-- Link to your CSS file -->

</head>

<body>

    <h2>Register</h2>

    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

        <label for="name">Name:</label>

        <input type="text" id="name" name="name" required>

        <br><br>

        <label for="email">Email:</label>

        <input type="email" id="email" name="email" required>

        <br><br>

        <label for="password">Password:</label>

        <input type="password" id="password" name="password" required>

        <br><br>

        <label for="confirm_password">Confirm Password:</label>

        <input type="password" id="confirm_password" name="confirm_password" required>

        <br><br>

        <label for="role">Role:</label>

        <select id="role" name="role" required>

            <option value="user" selected>User</option>

            <option value="admin">Admin</option>

        </select>

        <br><br>

        <input type="submit" value="Register">

    </form>

</body>

</html>


8. /user/cart/add_to_cart.php

<?php

include '../../includes/db_connect.php';

 

session_start();

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

$product_id = $_POST['product_id'];

$quantity = $_POST['quantity'];

$query = "INSERT INTO cart (user_id, product_id, quantity)

          VALUES ('$user_id', '$product_id', '$quantity')";

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

    echo "Product added to cart!";

} else {

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

}

?>


9. /user/orders/checkout.php

<?php

include '../../includes/db_connect.php';

session_start();

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

$total = $_POST['total'];

$query = "INSERT INTO orders (user_id, total) VALUES ('$user_id', '$total')";

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

    echo "Order placed successfully!";

} else {

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

}

?>


10. /products/product_list.php

<?php

include '../includes/db_connect.php';

$query = "SELECT * FROM products";

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

while ($product = mysqli_fetch_assoc($result)) {

    echo "Product: " . $product['name'] . " - Price: " . $product['price'] . "<br>";

}

?>


 

No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template