2
votes

Suppose a table for products in database. Now product has an "image" field where i will place the image name "image.jpg". Now i want to display more than one images of same product. image1.jpg, image2.jpg , image3.jpg.How can i add these records into that product table in single field and how to implement it in PHP to display those images. And the same scenario in terms of size of product i.e medium, large, extra large etc.

1
You do NOT put multiple pieces of data into a single field. That negates the purpose of having a relational database. You split that field into its own table so you can have as many image records in that subtable as you want.Marc B
Why would you do that? Can't you create another table with 1-N relationship in order to handle multiple images?loscuropresagio
OK thanks i will add an extra table for image, and do i have to do same for the size too?TPSstar
That depends on what you mean by saying "product". if in your scenario the same product cuold have more than one size, the answer is yes.loscuropresagio

1 Answers

0
votes

I will assume you have already weighed the pros and cons of storing a file name instead of storing a BLOB.

This sounds like a 1-to-many relationship. You will want a table that holds -- at a minimum -- the file name and a foreign key (FK) for the product table. Then you can have multiple images pointing to the same product FK. After that, in order to get the image for a single product, you would just do a query such as:

SELECT img.fileName
FROM image_table AS img
JOIN product_table prod ON prod.id = img.prod_id
WHERE prod.id = ID_THAT_YOU_WANT

I'm ignoring issues with SQL injection, but you shouldn't. Don't just append the ID to the query.