Programmatically setting images as thumbnails in Magento

Here's how to programmatically set uploaded images as a product's thumbnail, small image, and large image.

<?php
require_once 'app/Mage.php';
Mage::app();
mysql_connect(localhost, DATABASE_USER, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME) or die("Unable to select database");
$result = mysql_query("SELECT * FROM `catalog_product_entity_varchar` WHERE attribute_id in (74,75,76) AND value='no_selection'");
while ($row = mysql_fetch_array($result)) {
$id = $row["entity_id"];
$product = Mage::getModel("catalog/product")->load($id);
$mediaGallery = $product->getMediaGallery();
if ($mediaGallery["images"][0]["file"] != '' || $mediaGallery["images"][0]["file"] != NULL) {
$path = $mediaGallery["images"][0]["file"];
$update_result = mysql_query("UPDATE `catalog_product_entity_varchar` SET VALUE='".$path."' WHERE attribute_id in (74,75,76) and entity_id=".$id);
echo "set images for product ".$id."<br />";
}
}
?>

Importing products from Magento into Spree

Magento is evil. If you're working with its PHP codebase, I'm sorry. After looking for an easier, less dangerous solution, I found Spree. Easy to use, looks half decent out of the box, and built on Ruby on Rails, the slow but easy web framework. And there's a Heroku extension. Awesome.

One problem: The Magento installation had 9000 products, with names, descriptions, SKUs, and other fun attributes. Spree has no built-in import or export function. Do I want to enter all this information manually? No.

After some googling, yahooing, and asking jeeves, I found a Google group discussion, took some of the example code, tailored it to the CSV format of a standard Magento export, and ended up with this hack:
require 'fastercsv'
n = 0
FasterCSV.foreach("export_all_products.csv") do |row|
if n != 0
puts "Adding new product: #{row[7]}"
product = Product.new
product.name = row[7]
product.description = row[27]
product.sku = row[5].to_s
product.price = row[22].to_d
product.save!
end
n += 1
end
puts ""
puts "Import Completed - Added: #{n} Products"
view raw import.rb hosted with ❤ by GitHub
If you don't have the FasterCSV gem installed, install it before running this import script:
gem install fastercsv

Use the Rails runner to run this script so it has access to the database:
script/runner import.rb

and you're done.