0

I am working on a php based system.
Actually it is a product display system.
In the database there are 2 main tables called products, product_images

product

pid | product_name | weight | price | ....



product_images
iid | pid | image_path
Admin panel allows backend users to upload many images for a product.


That is the database table structure.
There are many products in the system.
There is a page which displays all the products with a image.
I used the below code to print all the products.

$getProduct = mysqli_query($con, "select p.*, pi.* from products p left join product_images pi on p.pid = pi.pid");
while($row = mysqli_fetch_array($getProduct)){
                    echo $row['product_name'].'<br>';
                    echo'<img src="../../thumbnails/'.$imgD['image_name'].'">';
                }

When I run the above code everything prints nicely but the images.
Image there is a product called "Sample Product #1" and has 4 photos.
The display page displays the product 4 times(It prints all 4 images).

<image> Sample Product #1<br>
<image> Sample Product #1<br>
<image> Sample Product #1<br>
<image> Sample Product #1<br>

What I need is to print the product name with the first image of the product.
How can I do this?

John Kreeda
  • 104
  • 6
  • 1
    Keep track of last printed `product_name` and don't print it again till you don't get same product name. ` $getProduct = mysqli_query($con, "SELECT p.*, pi.* FROM products AS p LEFT JOIN product_images pi ON p.pid = pi.pid ORDER BY product_name"); $productName = ''; while($row = mysqli_fetch_array($getProduct)){ if($productName != $row['product_name']) { $productName = $row['product_name']; echo $row['product_name'].'
    '; } echo''; } `
    – Ronak Dhoot Mar 22 '20 at 18:18
  • @RonakDhoot - Now the product name prints only once but all the images of the product prints. I need to print only the first image of the product. – John Kreeda Mar 23 '20 at 05:07

0 Answers0