Search code examples
phpunlink

Deleting a product with related pictures with PHP


In my PHP application I have products which have images in 3 sizes - big, thumbnails and small thumbnails. Each image is stored in a separate folder:

Images - /gallery Thumbnails - /gallery/bigthumbs Small thumbnails - /gallery/thumbs

Each product has its unique ID. The file names of all images of a certain product are the same. The path to the images for the product are being stored in the database with the same ID as the associated product ID.

Each product can have more than 1 image but in the database, where I store the paths and the names of the images for each product, all the images are stored with the same ID, the same as the product ID.

So, if a product with ID 56 has 2 images in the database, those images will be stored like this:

ID->56, image1name, bigthumb1name, thumb1name ID->56, image2name, bigthumb2name, thumb2name

What I'm trying to do is - delete all the images associated with the product which is being deleted. The code I've written is as follows:

$imagename_query = mysql_query("SELECT image FROM gallery WHERE id='$productid'", $connect);

$imagename_result = mysql_fetch_array($imagename_query);


    foreach($imagename_result as $imagename) {

    $bigimage = "../gallery/$imagename";
    unlink($bigimage);

    $picture = "../gallery/bigthumbs/$imagename";
    unlink($picture);

    $thumb = "../gallery/thumbs/$imagename";
    unlink($thumb);

 }

$gallery_query = mysql_query("DELETE FROM gallery WHERE id='$productid'", $connect); 


$query = mysql_query("DELETE FROM products WHERE ID='$productid'", $connect);

The problem is that the code above deletes only 1 image - no difference how many images there are with the same ID.

Could anybody help me figure this out?

Thanks in advance.


Solution

  • Thanks everybody for help. I've managed to solve this in the following way:

    $imagename_query = mysql_query("SELECT image FROM gallery WHERE id='$productid'", $connect);
    
        $rows_count = mysql_num_rows($imagename_query);
    
    for($i=0; $i<$rows_count; $i++){
    
        $id = mysql_result($imagename_query, $i, 'image');
    
        $bigimage = "../gallery/$id";
        unlink($bigimage);
    
        $picture = "../gallery/bigthumbs/$id";
        unlink($picture);
    
        $thumb = "../gallery/thumbs/$id";
        unlink($thumb);
    }
    

    Hope this will help somebody else.