I'm trying to come up with a database relation to keep track of purchased items that will be used for look up afterwards--for example ebooks. Ignore the ellipses--they represent miscellaneous data such as timestamp, etc...
Here's the table I have right now:
purchased:
transaction_id(int)(pk)(auto_inc) | username (varchar) | purchases (text) | ...
In this design, the column "purchases" is just a string of text that would contain the item_id of items purchased, separated by commas. Simplified example: "book1, book23, book5, book8".
In a successful transaction, this query would insert the transaction data into the "purchased" table:
INSERT INTO purchased VALUES (null, username, purchases, ...)
From this point on, two things can happen:
- The user can lookup what ebooks they've purchased
- The user can make another purchase transaction.
If the user (theusername) wants to see their ebooks, the system performs a selection query e.g.
SELECT purchases FROM purchased WHERE username=theusername
which returns a string containing the item IDs.
One a sidenot, is it possible to get an php array of purchases without having to use extra php code, i.e. explode? Can you use something besides the data type "text" in SQL to store a list of items? If not, that's okay.
Either way, here's the main problem. Say the user makes another transaction--there will now be two rows in "purchased" that contains the user's purchased items. That means that in this table, the user's purchases are split into multiple rows.
Ideally, I want these purchases to all be in the same row. I can't use an UPDATE statement because each purchase has it's own unique transaction_id.
I was thinking that I could make another table that contains all purchases by a user
all_purchased:
username (pk) | purchases (text) | ...
and whenever the user makes another transaction, the "all_purchased" table would just update its purchases column with the item ID of any new ebooks.
But this table seems redundant because the selection query I mentioned would get the task done.
What would be the best way to structure the database relation(s)?