Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Torger Angeltveit
Torger Angeltveit
11,228 Points

Adding a Product to a User with PHP & MYSQL database

Hi, i have 2 tables in my database:

Table1 - users id (PK) - name - email -password

Table2 - products product_id(PK) - title - image - info - price - category

I want the user to be able to add a product to a spesific user so he can view the product on his profile. But im not sure where to go from here? Could someone give me som guidelinds?

4 Answers

Casey Ydenberg
Casey Ydenberg
15,622 Points

The first thing to decide if this is a many-to-many relationship or a one-to-many relationship. It sounds like many-to-many: a user can add many products and a product can be added by more than one user.

If that's the case, you'll want to create another table of relationships between users and products. Usually this table has only two columns: the id in the users table and the id in the products table. If a row exists in the table associating a product with a user, then that relationship exists, if it doesn't it doesn't.

Exactly how you use this within your PHP code depends on how your project is set up, of course.

Torger Angeltveit
Torger Angeltveit
11,228 Points

Ok thanks! Yes its a many to many relatonship.

so i would create third table with user_id, and product_id and insert it trhough a form like this? $sql = "INSERT INTO users_products (user_id, product_id) VALUES ('$id', '$product_id')";

 <form action="#" method="post">
 <button name="add"></button>
 </form>

And to retrive the data i would use a SQL query with the JOIN method? or is there some other way to retrive the data?

Casey Ydenberg
Casey Ydenberg
15,622 Points

Yes, you'd probably want to use some kind of join (or two). To be honest my SQL is not that great - I tend to use frameworks that abstract this layer away and I'd have to look up how to do it. But this is how a framework would do it anyway.

Torger Angeltveit
Torger Angeltveit
11,228 Points

Ok, thanks for your reply, i think i will figure it out now :)