开发者

Effective way to store user selections in MySQL using PHP?

开发者 https://www.devze.com 2023-02-04 12:53 出处:网络
I\'m having trouble figuring out the best way to store what information my users want to see.I apologize for not being able to find an easy way to explain my problem, but here goes (the fruits are for

I'm having trouble figuring out the best way to store what information my users want to see. I apologize for not being able to find an easy way to explain my problem, but here goes (the fruits are for example's sake):

Let's say my users have an option to keep track of the following fruits in their fridge开发者_开发技巧:

Apples, Oranges, Grapes, Pears

The database is already setup with a table called 'fruits', where Apples is id_fruit=1, Oranges is id_fruit=2, etc.

Like I said all users have the OPTION to keep track of these fruits, however... I currently can not figure out an easy way to store the users selection of WHICH fruits they want to track. If user 1 doesn't like Apples, he can just go into his settings, uncheck Apples and no longer have Apples show up in his dashboard.

The only way I can think to store this information is to create a table that contains for fields user_id, apples, orange, grapes, pears. And then storing the user_id and Yes/No or 0/1 for the fruits.

This causes major grief if I ever want to add more fruits, or whatever.

What is the best way to store this information in MySQL, using PHP. And how would I retrieve that info.

User logs in, check the DB for which fruits he wants to see, and display only those fruits he has chosen.

Any help would be greatly appreciated.


This is a classic has-and-belongs-to-many, or simply many-to-many, relationship.

Table `users`
=============
id
name
...

Table `fruits`
==============
id
name
...

Table `users_fruits`
====================
id
user_id
fruit_id

In users_fruits you store one row per user-fruit relationship: (user_id: 42, fruit_id: 3).


Create a table tracking the actual relation.

You have one user table, with user id's. You have one fruit table, with fruit id's.

Create a table with user-fruit-relations. Let it have three colums, id, user_id and fruit_id.

If user 1 tracks fruits 2,3 and 5, insert those three rows in the table. That is, three rows with user_id = 1 and the different fruit_id's for each row.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号