Magento – how to set BaseImage, Small Image, Thumbnail to different images for each product in database

catalogimagemagento-1.7

I have imported a number of products at once, but the problem is: the Base Image, Small Image, Thumbnail are all set to the same image.

On the catalog page, I'm trying to change the image shown when you hover over a product. I believe, to do this, the small image and thumbnail image would need to be set to different images for the same product.

How can I achieve this?

I found below query, but I do not understand how to modify it to meet my requirement.

UPDATE
    catalog_product_entity_media_gallery AS mg,
    catalog_product_entity_media_gallery_value AS mgv,
    catalog_product_entity_varchar AS ev
SET
    ev.value = mg.value
WHERE
    mg.value_id = mgv.value_id
AND
    mg.entity_id = ev.entity_id
AND
    ev.attribute_id IN (70, 71, 72)
AND
    mgv.position = 1;

Please, can you help me find the right modifications.

Best Answer

Here is given programmatically adding media images to product, you can adjust this code to your own importing script:

    $mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')
        ->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'media_gallery');
    $mediaGallery          = $mediaGalleryAttribute->getBackend();
    $attrCode              = $mediaGalleryAttribute->getAttributeCode();


    $product          = Mage::getModel('catalog/product')->load($productId);
    $mediaGalleryData = $product->getData($attrCode);
    /**
     * If you want to remove old images use this code
     */
    if (isset($mediaGalleryData['images'])) {
        foreach ($mediaGalleryData['images'] as &$image) {
            $image['removed'] = 1;
        }
        $product->setData($attrCode, $mediaGalleryData);
    }
    /**
     * Here is real image file path
     */
    $thumbnailFile = 'real/path/to/thumbnail/file.jpg';
    $imageFile     = 'real/path/to/image/file.jpg';
    try {
        //Set thumbnail
        $imageFileUri = $mediaGallery->addImage($product, $thumbnailFile, null, false, false);
        $mediaGallery->setMediaAttribute($product, 'thumbnail', $imageFileUri);

        //Set image (or base image, small image whatever you want
        $imageFileUri = $mediaGallery->addImage($product, $imageFile, null, false, false);
        $mediaGallery->setMediaAttribute($product, 'image', $imageFileUri);
        $product->save();
    } catch (Exception $e) {
        Mage::logException($e);
    }