add a product to magento with php and mysql (programatically) - magento

this is the code I am using, it returns a server error. I am not sure why or what to do for it to work. any help would be greatly appreciated.
<?php
//product = Mage::getModel('catalog/product');
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$product = new Mage_Catalog_Model_Product();
$product->setSku("ABC123");
$product->setName("Type 7 Widget");
$product->setDescription("This widget will give you years of trouble-free widgeting.");
$product->setShortDescription("High-end widget.");
$product->setPrice(70.50);
$product->setTypeId('simple');
$product->setAttributeSetId(9); // need to look this up
$product->setCategoryIds("20,24"); // need to look these up
$product->setWeight(1.0);
$product->setTaxClassId(2); // taxable goods
$product->setVisibility(4); // catalog, search
$product->setStatus(1); // enabled
// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
$product->save();
// for stock
$stockData = $product->getStockData();
$stockData['qty'] = 10;
$stockData['is_in_stock'] = 1;
$stockData['manage_stock'] = 1;
$stockData['use_config_manage_stock'] = 0;
$product->setStockData($stockData);
?>

With Magento we can have several different ways to add products to the catalog. The way you are try to achieve need a few changes to work well. Please keep in mind that you should use as much of the Magento's functionalities, such as models, configs and so on.
A good approach for what you are looking for would be:
<?php
...
$product = Mage::getModel('catalog/product');
$product->setSku("SKUPROD123");
$product->setName("Name of The Product");
$product->setDescription("Some description of the product.");
$product->setShortDescription("Short one.");
$product->setPrice(299.50);
$product->setTypeId('simple');
$product->setAttributeSetId(9); // need to look this up
$product->setCategoryIds("20,24"); // need to look these up
$product->setWeight(1.8);
$product->setTaxClassId(2); // taxable goods
$product->setVisibility(4); // sets visibility as 'catalog, search'
$product->setStatus(1); // enabled
// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
$product->save();
I hope it helps

Related

Magento 1.9 Change Product Status Programmatically

I'm currently looking for a method to programmatically change the product status of all my products if a certain amount of stock is reached.
Ideally I would like to set all products to status Disabled if the Stock level is under 10. All others that are 10 and more , the product status should become Enabled.
You can try with this code by creating one php file to the root directory or you can create cron scheduler if you want to do this process for some time period.
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ini_set('memory_limit', '600M');
ini_set('max_execution_time', 1800);
umask(0);
Mage::app('admin');
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToSelect('*');
foreach ($collection as $_data) {
$productCat = $_data->getCategoryIds();
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_data);
$productqty = $stock->getQty();
if (intval($productqty) < 10) {
$productModel = Mage::getModel('catalog/product');
$productUpdate = $productModel->load($_data->getId());
$productUpdate->setStatus(2);
$productUpdate->save();
}
else
{
$productModel = Mage::getModel('catalog/product');
$productUpdate = $productModel->load($_data->getId());
$productUpdate->setStatus(1);
$productUpdate->save();
}
}

For loop is working only once

For the below code, where I am trying to update a custom attribute called branding. The for loop is running only for one iteration and stopping. It is updating only the first product in the list and not looping any further.
Can anyone kindly let me know why this is happening?
<?php
set_time_limit(0);
// require magento core
require_once 'app/Mage.php';
// execute on admin store
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $product){
echo $product->getSku();
$product->setData('branding', 'kib');
$product->save();
}
Instead of saving total product just save attribute for product by using saveAttribute
// require magento core
require_once 'app/Mage.php';
// execute on admin store
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
echo $products->getSelect();//this will give sql query just run your db.
foreach($products as $product)
{
$product->setBranding('kib');
$product->getResource()->saveAttribute($product, 'branding');
}
One more solution without loops
$store_id = 0;
$product_ids = Mage::getModel('catalog/product')
->getCollection()
->getAllIds();//you can apply some filters also
Mage::getSingleton('catalog/product_action')->updateAttributes(
$product_ids,//array of ids
array('branding' => 'kib'),//you can add some other attributes also as key value pair
$store_id
);

Updating Meta Title in Magento via PHP script causes unwanted events

On our Magento 1.5.0.1 I wrote a PHP script to update all of our product meta titles to be based on the name and SKU of each product. The script is run by calling PHP via SSH.
After running the script I noticed in our M2E Pro (the eBay syncing module) that every single product appears to have become disabled.
Looking at the actual products they aren't disabled, so it appears my script is somehow faking the event.
Out of our 3,000+ products, though, one of them was disabled and subsequently M2E Pro removed the listing from eBay.
Here is my script:
<?php
set_time_limit(0);
define('MAGENTO', "/home/discount/public_html");
require_once MAGENTO . '/app/Mage.php';
error_reporting(E_ALL);
ini_set('display_errors', '1');
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$storeId = Mage::app()->getStore('default')->getId();
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('sku')
->addAttributeToSelect('name')
->addAttributeToSelect('meta_title');
$total = count($products);
$count = 1;
foreach ($products as $product)
{
$mt = sprintf("%s [%s]", $product->getName(), $product->getSku());
$sku = $product->getSku();
if ($product->getMetaTitle() != $mt)
{
$percent = $count / $total;
echo $sku." ".$percent."\n";
$product->setMetaTitle($mt);
$product->save();
}
}
?>
I'd like to know what I need to do to my script to make it correctly update the meta title without causing odd events?
Stab in the dark here, but it's a good chance the M2E extension has an event listener setup for model/product saves, and in that event listener does things depending on product state.
By itself this isn't a problem, but when you load an EAV model via its collection it loads the bare minimum of attributes. Since you haven't explicitly loaded product status via addAttributeToSelect this may be confusing the M2E extension. Trying adding the status attribute. If that doesn't work try addAttributeToSelect('*') — M2E may be checking other attributes as well to decide when to pull things.
Finally, when you load an EAV model via a collection their afterLoad isn't called. It's possible the M2E extension (naively) assumes something that happens in afterLoad will have happened, so you may want to call it explicitly for each product.
$product->afterLoad();
Short of that, you'll need to reverse engineer M2E to the point in the code where it's doing it's above logging and determine why it thinks it needs to disable a product. Since this is a commercial extension, I'd reach out to the developers. If you pay for something you deserve some level of support.
<?php
//increase the max execution time
#ini_set('max_execution_time', -1);
//memory_limit
#ini_set('memory_limit', -1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Start Despaly All Product Meta Title And Description
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$categories = Mage::getModel('catalog/category')
->getCollection()
// magic is prepared here..
->addAttributeToSelect('*')
// then the magic happens here:
->addAttributeToFilter('level', array('eq'=>4))
->load();
if (count($categories) > 0):
foreach($categories as $category):
$catId = $category->getId();
$category = Mage::getModel('catalog/category')->load($catId);
$resource = Mage::getResourceModel('catalog/category');
//if($catId==1465): //If Update Specific category Value by Id
$CategoryName = $category->getName();
$metaTitle = "Buy ".$CategoryName." Test Title";
$metaDescription = "Shop your favourite ".$CategoryName." Test Description";
$category->setData('meta_title', $metaTitle);
$resource->saveAttribute($category, 'meta_title');
$category->setData('meta_description', $metaDescription);
$resource->saveAttribute($category, 'meta_description');
$check = $category->getMetaTitle();
echo "<pre>";
print_r($catId);
echo "<pre>";
print_r($check);
echo "\n";
//endif;
endforeach;
else: echo "No Results";
endif;
?>

Magento fill cart from external script with different storeviews

I have a small script, which fills my magento shopping cart with products. It's used for a quickorder form. So it gets called with /quickorder.php?sku1=123&qty1=1&sku2=124&qty2=1 etc.
It's working well for my default store, but for the second store, it seems as it always wants to fill the default shopping cart. At least it redirects me to the default cart url.
How can I get this working to add products to my cart whatever store I'm currently in?
Thanks in advance
<?php
require_once 'app/Mage.php';
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend')); // Session erzeugen
$Cart = Mage::getSingleton('checkout/cart'); // Instanz zum Warenkorb
for ($count=1; $_POST['sku'.$count]!=''; $count++) {
$sku = $_POST['sku'.$count];
$qty = $_POST['qty'.$count];
$catprod = Mage::getModel('catalog/product');
$product_id = $catprod->getIdBySku($sku);
if ($product_id) {
$ProdObj = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($product_id); // Produkt laden
$Cart->addProduct($ProdObj, $qty); // Produkt in den Warenkorb einfügen
Mage::getSingleton('checkout/session')->addSuccess('Artikelnummer "'.$sku.'" wurde '.$qty.'x hinzugefügt.');
} else Mage::getSingleton('checkout/session')->addError('Artikelnummer "'.$sku.'" wurde nicht gefunden.');
}
$Cart->save(); // Warenkorb speichern
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
header('Location: '. Mage::getUrl('checkout/cart'));
?>
You can get store id by product, like below :
$productModel = Mage::getModel('catalog/product');
$product_id = $productModel->load($object->getId());
$store_id = $product_id->getStoreId();

Magento 1.5.1 getting product images using php

This code gets contents(images) in a magento store. It is able to fetch images for magento 1.4x - 1.5
I tried it in 1.5.1 and it seems it cannot fetch the images. Is it located in "media/catalog/product" ?
Any help in getting the location of magento 1.5.1 images? Thanks.
<?php
include_once 'app/Mage.php';
umask(0);
Mage::app();
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('*');
$products->load();
$baseUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
$myImage = $baseUrl ."media/catalog/product". $product['image'];
?>
<?php
include_once 'app/Mage.php';
umask(0);
Mage::app();
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('thumbnail');
$products->load();
$product = $products->getData('thumbnail');
$baseUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
$myImage = $baseUrl ."media/catalog/product". $product[2]['thumbnail'];
print $myImage;
?>
Obviously you'll want to loop over the collection or specify a product ID in your collection for a specific product, I just used an index of [2] for show.
Also no need to load the entire product attributes collection with * but rather the specific attribute your needing to conserve memory space.

Resources