Most viewed product in e-commerce website

 If you want to show the most viewed products by a single user without storing views in a database, you can achieve this by tracking views using session variables in PHP. Here's a simplified example:


1. **PHP Session Setup**: Ensure that you have session support enabled in your PHP configuration. You can start a session at the beginning of your PHP script using `session_start()`.


2. **Track Product Views**:

   - When a user views a product page, you can store the viewed product IDs in a session variable.

   - If the session variable doesn't exist, create it as an array. If it already exists, append the product ID to the array.


3. **Count Product Views**:

   - After tracking views for a user session, you can count the frequency of each product ID in the session array to determine the most viewed products.


Here's a simplified example in PHP:


```php

<?php

// Start or resume the session

session_start();


// Function to track product views

function trackProductView($productId) {

    // Check if the session variable 'viewed_products' exists

    if (!isset($_SESSION['viewed_products'])) {

        // If it doesn't exist, create it as an empty array

        $_SESSION['viewed_products'] = [];

    }


    // Append the product ID to the viewed products array

    $_SESSION['viewed_products'][] = $productId;

}


// Sample product IDs (you can replace these with your actual product IDs)

$productId1 = 1;

$productId2 = 2;

$productId3 = 3;


// Simulate product views (call this function when a user views a product page)

trackProductView($productId1);

trackProductView($productId2);

trackProductView($productId1);

trackProductView($productId3);

trackProductView($productId2);


// Count the frequency of each product ID in the viewed products array

$viewedProductCounts = array_count_values($_SESSION['viewed_products']);


// Sort products by view count in descending order

arsort($viewedProductCounts);


// Display the most viewed products

echo "Most Viewed Products:<br>";

foreach ($viewedProductCounts as $productId => $count) {

    echo "Product $productId - Views: $count<br>";

}


// Clear the viewed products session data (optional)

unset($_SESSION['viewed_products']);

?>

```


In this example:


- We start or resume the PHP session using `session_start()`.

- The `trackProductView` function tracks product views by appending the product ID to the session array `'viewed_products'`.

- We simulate product views using sample product IDs.

- We count the frequency of each product ID using `array_count_values` and sort them in descending order to determine the most viewed products.


Keep in mind that this example stores views for the current session, so if a user closes their browser or session expires, the views will be lost. For a more persistent solution, consider storing views in a database.

Previous
Next Post »