I'm creating a token based rest api in php for e-commerce application.
Scenario :
Any visitor can add items to cart without logging in. These items are stored in the mysql database, cart table, with user_id value which defaults to 1. // As user is not logged in.
Problem :
After the user logs in, i am able to fetch the userid after decoding the token generated for the user, but want to know, how can i identify which items in cart table belongs to which user so as to update the actual userid against those products ?
Table :
customer_id int(11),
item_id int(11),
quantity int(11),
date_added datetime
Thanks in advance for any help!
You simply can't do it this way. You obviously a field in database which will be the same before, and after the user logs in. For exemple you could try to store an IP address or MAC address when user is not logged in. Then when user is logged in, you search for same values (on IP or Mac address) on the cart table, and set all the matching elements to the user ID.
In anycase, you'll obviously need to store something unique that will make a relation between then cart and the user.
Another solution, maybe the best corresponding to your needs, is to store the cart of unidentified users in cookies. Then, when users logs in, you'll have to browse all items stored in cookies to add them in your database with a correct user ID.
You should generate a (temporary) identification. I'd add an auto incremented column to your database id
. After you have created the database you can retrieve the id with something like PDO mysqli_insert_id($conn)
. Store that id in a PHP session and you have it!