Skip to content

Instantly share code, notes, and snippets.

@shopglobal
Last active August 21, 2024 23:47
Show Gist options
  • Save shopglobal/5023b920c0e8db69e38b1e9acad957d0 to your computer and use it in GitHub Desktop.
Save shopglobal/5023b920c0e8db69e38b1e9acad957d0 to your computer and use it in GitHub Desktop.
Multi user marketplace

To create this marketplace with multi-user authentication in PHP, you'll need to build several key components:

1. User Authentication

  • Registration and Login:

    • Create a registration system where users sign up with their email and password.
    • Implement a login system with proper password hashing (e.g., using password_hash() and password_verify() in PHP).
  • Session Management:

    • Use PHP sessions to keep users logged in and maintain their state across pages.

2. Database Design

  • Users Table:

    • Columns: id, username, email, password, balance.
  • Items Table:

    • Columns: id, user_id (FK to Users table), title, description, price, category, created_at.
  • Categories Table:

    • Columns: id, name, user_id (FK to Users table), created_at.
  • Transactions Table:

    • Columns: id, buyer_id (FK to Users table), seller_id (FK to Users table), item_id (FK to Items table), amount, transaction_date.

3. User Balance Management

  • Function to Update Balance:

    • Create a PHP function to update the user's balance based on external transactions or actions (e.g., updateBalance($userId, $amount)).
  • Payment from Balance:

    • Deduct the item cost from the buyer’s balance and credit the seller’s balance.

4. Listing Items

  • Item Creation:

    • Allow users to create listings by providing a title, description, price, and a category.
    • Users can create custom categories if desired.
  • Listing Display:

    • Display listed items with their categories, seller information, and price.
    • Implement search and filter functionality by categories.

5. Purchasing Items

  • Transaction Process:
    • When a buyer purchases an item, deduct the item price from their balance, add it to the seller’s balance, and create a record in the Transactions table.

6. Admin Panel (Optional)

  • Category Management:
    • Admins can manage categories (create, edit, delete) to keep the marketplace organized.

7. Security Considerations

  • Input Validation:

    • Validate and sanitize all user inputs to prevent SQL injection and XSS attacks.
  • Secure Passwords:

    • Use strong hashing algorithms and secure session management.

8. Code Snippets:

  • User Registration:

    // Register new user
    function registerUser($username, $email, $password) {
        $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
        $query = "INSERT INTO users (username, email, password, balance) VALUES (?, ?, ?, 0)";
        // Execute query with prepared statements
    }
  • Balance Update:

    function updateBalance($userId, $amount) {
        $query = "UPDATE users SET balance = balance + ? WHERE id = ?";
        // Execute query with prepared statements
    }
  • Create Listing:

    function createListing($userId, $title, $description, $price, $category) {
        $query = "INSERT INTO items (user_id, title, description, price, category, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
        // Execute query with prepared statements
    }
  • Purchase Item:

    function purchaseItem($buyerId, $itemId) {
        // Get item price and seller information
        $item = getItemById($itemId);
        $price = $item['price'];
        $sellerId = $item['user_id'];
    
        // Begin transaction
        startTransaction();
    
        // Deduct from buyer's balance
        updateBalance($buyerId, -$price);
    
        // Credit to seller's balance
        updateBalance($sellerId, $price);
    
        // Record transaction
        recordTransaction($buyerId, $sellerId, $itemId, $price);
    
        // Commit transaction
        commitTransaction();
    }

This approach covers the basic requirements of your marketplace. Depending on your needs, you may want to add more features like order tracking, messaging between users, or a rating system.

To integrate MySQL with your PHP-based marketplace, you'll need to set up a MySQL database, connect to it using PHP, and execute SQL queries for user authentication, item management, and transaction handling. Below is a step-by-step guide on how to integrate MySQL into your PHP marketplace:

1. Set Up MySQL Database

  • Create a MySQL Database:

    CREATE DATABASE marketplace_db;
  • Create Tables:

    USE marketplace_db;
    
    -- Users Table
    CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL,
        email VARCHAR(100) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        balance DECIMAL(10, 2) DEFAULT 0.00
    );
    
    -- Items Table
    CREATE TABLE items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT,
        title VARCHAR(100) NOT NULL,
        description TEXT NOT NULL,
        price DECIMAL(10, 2) NOT NULL,
        category VARCHAR(50) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
    );
    
    -- Categories Table
    CREATE TABLE categories (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL,
        user_id INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
    );
    
    -- Transactions Table
    CREATE TABLE transactions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        buyer_id INT,
        seller_id INT,
        item_id INT,
        amount DECIMAL(10, 2) NOT NULL,
        transaction_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (buyer_id) REFERENCES users(id),
        FOREIGN KEY (seller_id) REFERENCES users(id),
        FOREIGN KEY (item_id) REFERENCES items(id)
    );

2. Connect PHP to MySQL

  • Database Connection Script (db.php):
    <?php
    $host = 'localhost';
    $db = 'marketplace_db';
    $user = 'root';  // Replace with your MySQL username
    $pass = '';      // Replace with your MySQL password
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("Could not connect to the database: " . $e->getMessage());
    }
    ?>

3. User Registration Example

  • Register User (register.php):
    <?php
    require 'db.php';
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $username = $_POST['username'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
        $stmt->execute([$username, $email, $hashedPassword]);
    
        echo "User registered successfully!";
    }
    ?>
    <form method="POST" action="register.php">
        <input type="text" name="username" placeholder="Username" required>
        <input type="email" name="email" placeholder="Email" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Register</button>
    </form>

4. User Login Example

  • Login User (login.php):
    <?php
    require 'db.php';
    session_start();
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $email = $_POST['email'];
        $password = $_POST['password'];
    
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
    
        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            echo "Login successful!";
        } else {
            echo "Invalid email or password.";
        }
    }
    ?>
    <form method="POST" action="login.php">
        <input type="email" name="email" placeholder="Email" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>

5. Creating and Listing Items

  • Create Item (create_item.php):

    <?php
    require 'db.php';
    session_start();
    
    if (!isset($_SESSION['user_id'])) {
        die("You must be logged in to list an item.");
    }
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $userId = $_SESSION['user_id'];
        $title = $_POST['title'];
        $description = $_POST['description'];
        $price = $_POST['price'];
        $category = $_POST['category'];
    
        $stmt = $pdo->prepare("INSERT INTO items (user_id, title, description, price, category) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$userId, $title, $description, $price, $category]);
    
        echo "Item listed successfully!";
    }
    ?>
    <form method="POST" action="create_item.php">
        <input type="text" name="title" placeholder="Item Title" required>
        <textarea name="description" placeholder="Description" required></textarea>
        <input type="number" step="0.01" name="price" placeholder="Price" required>
        <input type="text" name="category" placeholder="Category" required>
        <button type="submit">List Item</button>
    </form>
  • Display Items (list_items.php):

    <?php
    require 'db.php';
    
    $stmt = $pdo->query("SELECT items.*, users.username FROM items JOIN users ON items.user_id = users.id");
    $items = $stmt->fetchAll();
    
    foreach ($items as $item) {
        echo "<h2>{$item['title']}</h2>";
        echo "<p>{$item['description']}</p>";
        echo "<p>Price: {$item['price']}</p>";
        echo "<p>Category: {$item['category']}</p>";
        echo "<p>Seller: {$item['username']}</p>";
        echo "<hr>";
    }

6. Handling Transactions

  • Purchase Item (purchase_item.php):
    <?php
    require 'db.php';
    session_start();
    
    if (!isset($_SESSION['user_id'])) {
        die("You must be logged in to purchase an item.");
    }
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $buyerId = $_SESSION['user_id'];
        $itemId = $_POST['item_id'];
    
        // Fetch item and seller info
        $stmt = $pdo->prepare("SELECT * FROM items WHERE id = ?");
        $stmt->execute([$itemId]);
        $item = $stmt->fetch();
    
        if ($item) {
            $price = $item['price'];
            $sellerId = $item['user_id'];
    
            // Begin transaction
            $pdo->beginTransaction();
    
            // Deduct from buyer's balance
            $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            $stmt->execute([$price, $buyerId]);
    
            // Credit to seller's balance
            $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->execute([$price, $sellerId]);
    
            // Record transaction
            $stmt = $pdo->prepare("INSERT INTO transactions (buyer_id, seller_id, item_id, amount) VALUES (?, ?, ?, ?)");
            $stmt->execute([$buyerId, $sellerId, $itemId, $price]);
    
            // Commit transaction
            $pdo->commit();
    
            echo "Purchase successful!";
        } else {
            echo "Item not found.";
        }
    }
    ?>
    <form method="POST" action="purchase_item.php">
        <input type="hidden" name="item_id" value="ITEM_ID_TO_PURCHASE">
        <button type="submit">Buy Now</button>
    </form>

7. Security and Error Handling

  • Input Validation and Sanitization:

    • Always validate and sanitize user inputs using functions like filter_var() and htmlspecialchars().
  • Error Handling:

    • Use try...catch blocks around database operations to handle potential errors gracefully.

8. Additional Features

  • You can add features such as an admin panel, messaging between users, or a rating system based on your specific needs.

This setup provides a solid foundation for your PHP-based marketplace with MySQL integration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment