How to add functionality of "Recently visited products" on an ecommerce website?
I am working on an e-commerce website (online shopping) which sells various products. I want to show the user a list of products that the user has browsed recently. Can you please help me in achieving this?
I am using PHP, MySQL,开发者_如何学运维 Apache HTTP on a Windows server.
Thanks!!
You could use a database or cookie. This database method will persist even after users clear their browser cookies:
Create a table in your database something like:
userid,
productid,
viewdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
Whenever a visitor views a product, you simply insert a row into the database identifying the user, the product, and a timestamp of when it was visited.
-- Insert
INSERT INTO recentlyviewed (userid, productid) VALUES (userid, productid);
Next time the user loads a page, you retrieve the most recent n products they viewed and display them. Periodically, you can run a scheduled job to clean up view records older than some number of days you've chosen to expire them.
-- Cleanup old records after 14 days
DELETE FROM recentlyviewed WHERE viewdate < DATE_ADD(NOW(), INTERVAL -14 DAY);
There are two ways, that I can think of, to do this.
- You can store which products they've viewed in a cookie.
- You can store their session_id in a database and then store the viewed products in there related to the session_id.
I think the second option is the better as you can then use this data to create some kind of 'people who viewed this product also view this one' like Amazon have
Here is how I would do it, you create a table like this:
CREATE TABLE views(
id bigint not null auto_increment,
user_id bigint not null,
product_id bigint not null,
primary key(id)
)
And every time a user views a product, you save the user's id and the product id here. You can then using a simple select query get the latest 10 products a user has viewed, as well as get the view count for a single product.
精彩评论