Reputation: 11257
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!!
Upvotes: 4
Views: 5132
Reputation: 12867
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.
Upvotes: 0
Reputation: 1254
There are two ways, that I can think of, to do this.
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
Upvotes: 2
Reputation: 270607
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);
Upvotes: 3