Wishlist items when being fetch from the session display blank

Hi Team

I am adding an item fine from my wishlist, issue now i am unable to displaying these item from my wishlist when being logged in successful as an existing user. I need some help, i think i am missing some step on my below code;

// server side code
<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'logs/roundcube/errors.log'); 

session_start();

if (isset($_POST['productId'])) {
    $productId = $_POST['productId'];

    // Replace with your database connection details
    $host = 'localhost';
    $dbname = 'estdb';
    $username = 'root';
    $password = '';

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        if (isset($_SESSION['user_id'])) {
            // User is logged in
            $userId = $_SESSION['user_id'];

            // Check if the item already exists in the user's wishlist
            $stmt = $pdo->prepare("SELECT * FROM wishlist WHERE user_id = ? AND product_id = ?");
            $stmt->execute([$userId, $productId]);
            $wishlistItem = $stmt->fetch(PDO::FETCH_ASSOC);
            var_dump($wishlistItem);

            if ($wishlistItem) {
                // Item already exists in the user's wishlist
                echo json_encode(['success' => false, 'message' => 'Item is already in the wishlist.']);
            } else {
                // Fetch product details from the database
                $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
                $stmt->execute([$productId]);
                $product = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($product) {
                    // Item doesn't exist in the user's wishlist, so add it
                    $stmt = $pdo->prepare("INSERT INTO wishlist (user_id, product_id, product_name, product_image, product_price, quantity) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$userId, $productId, $product['product_name'], $product['product_image'], $product['product_price'], 1]);

                    echo json_encode(['success' => true, 'message' => 'Item added to the wishlist.']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Product not found in the database.']);
                }
            }
        } else {
            // User is not logged in
            // Save the item to the session wishlist
            if (!isset($_SESSION['wishlist'])) {
                $_SESSION['wishlist'] = array();
            }

            if (!in_array($productId, $_SESSION['wishlist'])) {
                $_SESSION['wishlist'][] = $productId;
            }

            echo json_encode(['success' => true, 'message' => 'Item added to the wishlist.']);
        }
    } catch (PDOException $e) {
        if ($e->getCode() === '23000') {
             $error_message = 'An error occurred: ' . $e->getMessage();
            
             error_log($error_message);
            // Handle duplicate entry error
            echo json_encode(['success' => false, 'message' => 'Item is already in the wishlist.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
} elseif (isset($_POST['login'])) {
    // This part of the code handles user login
    // You should validate the user's login credentials here

    $username = $_POST['username'];
    $password = $_POST['password'];

    // Perform user authentication here, check if the user exists in the database

    // If the user is successfully authenticated, set their user ID in the session
    // You should replace this with your own authentication logic
    $_SESSION['user_id'] = 1; // Replace 1 with the actual user ID

    // After successful login, fetch and return the user's wishlist items
    if (isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];

    // Fetch the user's wishlist items from the database
    $stmt = $pdo->prepare("SELECT * FROM wishlist WHERE user_id = ?");
    $stmt->execute([$userId]);
    $wishlistItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Output the wishlist items as JSON for JavaScript to handle
    echo json_encode($wishlistItems);
}
}
?>

// javascript code

document.addEventListener('DOMContentLoaded', async function() {
    // Initialize wishlist count and items
    let wishlistCount = 0;
    let wishlistItems = [];

    // Function to update the wishlist badge count
    function updateWishlistBadge() {
        document.getElementById("wishlist-badge").textContent = wishlistCount;
    }

    // Function to open the login modal
    function openLoginModal() {
        $('#wishlistLoginModal').modal("show");
    }

    // Function to display wishlist items
    function displayWishlist(wishlistItems) {
        console.log('Received wishlist items:', wishlistItems);
        const wishlistTable = document.getElementById('wishlistTable').getElementsByTagName('tbody')[0];
        wishlistTable.innerHTML = ''; // Clear existing items

        wishlistItems.forEach((item) => {
            console.log('Processing item:', item);
            const row = wishlistTable.insertRow();
            const cell1 = row.insertCell(0);
            const cell2 = row.insertCell(1);
            const cell3 = row.insertCell(2);
            const cell4 = row.insertCell(3);

            cell1.textContent = item.product_name; // Change this to match your data structure
            cell2.innerHTML = `<img src="${item.product_image}" alt="${item.product_name}" class="img-thumbnail">`; // Change this to match your data structure
            cell3.textContent = 'R' + item.product_price.toFixed(2); // Change this to match your data structure
            cell4.textContent = item.quantity; // Change this to match your data structure
        });
    }

    // Load wishlist items and count from the session when the page loads
    wishlistItems = JSON.parse(sessionStorage.getItem('wishlistItems')) || [];
    wishlistCount = parseInt(sessionStorage.getItem('wishlistCount')) || 0;
    updateWishlistBadge();

    // Listen for the "Add to Wishlist" button click
    document.querySelectorAll(".add-to-wishlist-btn").forEach(button => {
        button.addEventListener('click', async function() {
            const productId = this.dataset.productId;
            console.log("Product ID:", productId);
            const productName = this.dataset.productName;
            console.log("Product Name:", productName);
            const productImage = this.dataset.productImage;
            console.log("Product Image", productImage);

            // Simulate adding an item to the wishlist
            wishlistCount++;
            updateWishlistBadge();
            wishlistItems.push({ productId, productName, productImage });
            

            // Store wishlist items and count in session
            sessionStorage.setItem('wishlistItems', JSON.stringify(wishlistItems));
            sessionStorage.setItem('wishlistCount', wishlistCount);
        });
    });

    // Listen for the "Wishlist" badge click
    document.getElementById("wishlist-badge").addEventListener('click', function() {
        console.log("Wishlist badge clicked");
        if (wishlistCount > 0) {
            // Display the login modal
            openLoginModal();
        }
    });

    // When the user logs in successfully, call this function to display wishlist items
    async function onLogin() {
        if (wishlistCount > 0) {
            fetchWishlistItems().then((wishlistItems) => {
             console.log('Received wishlist items:', wishlistItems);
        displayWishlist(wishlistItems);
});
        }
    }

    // Function to fetch wishlist items from the server
    // Function to fetch wishlist items from the server
async function fetchWishlistItems() {
    try {
        const response = await fetch('get-wishlist-items.php', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        console.log('Fetch response:', response);

        if (response.ok) {
            const wishlistItems = await response.json();
            console.log('Received wishlist items:', wishlistItems);
            return wishlistItems;
        } else {
            console.error('Error fetching wishlist items:', response.status);
            return [];
        }
    } catch (error) {
        console.error('Error fetching wishlist items:', error);
        return [];
    }
}

});

this what is debugged from client side
Product ID: 10
index.html:1166 Product Name: Golf T-Shirt
index.html:1168 Product Image img/wishlist-img/SecondWishlist.jpg
index.html:1183 Wishlist badge clicked

So where in your code do you call onLogin?

What is the code for get-wishlist-items.php? You need specific server-side code that gets the data and outputs it in the correct format for the client-side code to use.

You should also have a single storage location for the data, regardless of the logged in user state. By having two different storage locations, not only do you have two sets of code, but now you must manage what happens with the data when the logged in state changes. You need to only use $_SESSION data or use a database table for the initial storage location, not both. If you use $_SESSION data, you would need to move the data to a database table when the user finalizes the list.

typo, i dont have that function i relies it now and busy implementing it.

 I noticed that you’re not handling the case where the user logs in and there are items in the session wishlist ($_SESSION['wishlist']

). These items should be transferred to the database wishlist for that user.

You can add a piece of code that runs when the user logs in, which checks if there are any items in

$_SESSION['wishlist']

, and if so, adds those items to the database wishlist for that user.

Can you perhaps show me how to do this, this is where i am now stuck because i am not seeing any insert to the table on the database.

yeah you could give it a try, here we go!!

if (isset($_SESSION['wishlist']) && !empty($_SESSION['wishlist'])) {
    // User has just logged in and there are items in the session wishlist
    foreach ($_SESSION['wishlist'] as $item) {
        // Your database insert query here
        // For example: INSERT INTO user_wishlist (user_id, item_id) VALUES (?, ?)
    }
    // Clear the session wishlist after transferring to database
    unset($_SESSION['wishlist']);
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.