i have use below code to add product in magento but not success ,anyone know how to do?
code here
code txt file
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('A123');
$product->setAttributeSetId(4);
$product->setTypeId('simple');
$product->setName('Some cool product name');
$product->setCategoryIds(array(19));
$product->setWebsiteIDs(array(1));
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setPrice(39.99);
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0);
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
}
catch (Exception $ex) {
}
?>
i hope it may bemage.php path issue.Try put proper of mage file path
Suppose,My Magento path is /home/abc/www/www/ in server.
and my script file location location in /home/abc/www/www/try/dot/myscript.php
If you try to include mage.php from myscript.php then
$mageFilename = '/home/abc/www/www/app/Mage.php'
or
$mageFilename = '../../app/Mage.php'
i have run your script with modify mage.php file location call in script.it is works
I've been using this code to add/update products on Magento.
<?php
include_once("app/Mage.php");
Mage::app();
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$counter = 0;
I have this function to get (or create) a product by SKU:
function GetProduct($sku)
{
global $counter;
echo $sku;
$p = Mage::getModel('catalog/product');
$productId = $p -> getIdBySku($sku);
if($productId)
{
echo "!";
$p -> load( $productId );
}
else
{
$p->setTypeId('simple');
$p->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$p->setStatus(1);
$p->setTaxClassId(7);
$p->setWebsiteIDs(array(1));
$p->setStoreIDs(array(1));
$p->setAttributeSetId(4);
$p->setSku($sku);
}
echo "...";
$counter++;
echo " ".$counter;
return $p;
}
Here's the function to save the product:
function SaveProduct($p)
{
try
{
if (is_array($errors = $p->validate()))
{
$strErrors = array();
foreach($errors as $code=>$error)
{
$strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
echo $strErrors[0];
}
$this->_fault('data_invalid', implode("\n", $strErrors));
}
$p->save();
echo "\n";
}
catch (Mage_Core_Exception $e)
{
$this->_fault('data_invalid', $e->getMessage());
}
}
And finally I'm calling like this:
$product = GetProduct('sku1');
$product->setData('thumbnail_label', 'sku1');
SaveProduct($product);
unset($product);
$product = GetProduct('sku2');
$product->setData('url_path', 'plastic-hat.html');
SaveProduct($product);
unset($product);
$product = GetProduct('sku3');
$product->setData('thumbnail_label', 'sku3');
SaveProduct($product);
unset($product);
$product = GetProduct('sku4');
$product->setData('thumbnail_label', 'sku4');
SaveProduct($product);
unset($product);
$product = GetProduct('sku5');
$product->setData('thumbnail_label', 'sku5');
SaveProduct($product);
unset($product);
I run this code from the command-line as there is a memory leak running it this way. You can only get so many products updated before it blows the memory and you have to edit and re-run the code to keep going, but it works and it's relatively fast.
You should be able to slot your code in quite nicely.
Related
I'm working on magento using Magento 1.X API. I want to create products in magento so I'm using catalogProductCreate method to create.
This is working great when it is around 5 to 10 products, but when trying to insert multiple products it is taking a lot of time.
Is there any method to insert bulk products at a time.
The API/programmatic/dataflow method of adding products in Magento is notoriously slow when dealing with large data sets.
If you haven't already looked at it, try Magmi - it is the missing piece of Magento catalogue management. You can add/update thousands of products in minutes with spreadsheets. It can also be called on CLI which opens up lots of excellent automation possibilities.
Oh, and best of all - it's free.
https://github.com/dweeves/magmi-git
I've been using this code to add/update products on Magento.
<?php
include_once("app/Mage.php");
Mage::app();
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$counter = 0;
I have this function to get (or create) a product by SKU:
function GetProduct($sku)
{
global $counter;
echo $sku;
$p = Mage::getModel('catalog/product');
$productId = $p -> getIdBySku($sku);
if($productId)
{
echo "!";
$p -> load( $productId );
}
else
{
$p->setTypeId('simple');
$p->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$p->setStatus(1);
$p->setTaxClassId(7);
$p->setWebsiteIDs(array(1));
$p->setStoreIDs(array(1));
$p->setAttributeSetId(4);
$p->setSku($sku);
}
echo "...";
$counter++;
echo " ".$counter;
return $p;
}
Here's the function to save the product:
function SaveProduct($p)
{
try
{
if (is_array($errors = $p->validate()))
{
$strErrors = array();
foreach($errors as $code=>$error)
{
$strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
echo $strErrors[0];
}
$this->_fault('data_invalid', implode("\n", $strErrors));
}
$p->save();
echo "\n";
}
catch (Mage_Core_Exception $e)
{
$this->_fault('data_invalid', $e->getMessage());
}
}
And finally I'm calling like this:
$product = GetProduct('sku1');
$product->setData('thumbnail_label', 'sku1');
SaveProduct($product);
unset($product);
$product = GetProduct('sku2');
$product->setData('url_path', 'plastic-hat.html');
SaveProduct($product);
unset($product);
$product = GetProduct('sku3');
$product->setData('thumbnail_label', 'sku3');
SaveProduct($product);
unset($product);
$product = GetProduct('sku4');
$product->setData('thumbnail_label', 'sku4');
SaveProduct($product);
unset($product);
$product = GetProduct('sku5');
$product->setData('thumbnail_label', 'sku5');
SaveProduct($product);
unset($product);
I run this code from the command-line as there is a memory leak running it this way. You can only get so many products updated before it blows the memory and you have to edit and re-run the code to keep going, but it works and it's relatively fast.
I'm using magento EE 1.14.2.1.I have about 50k products in databases.I just want some useful advice about updating products.
As I mentioned in title , in everyday I have about 5k product need to be update stock and price.So,should I do it in midnight then reindex them all in one time or turn on the enterprise refresh index cron and update product in many times in a day ( about 100 product per times ).The most important thing which I concerted is the website performance and avoiding MySQL deadlock.
Here's an option for you. I have an import.php script that I use to import or update large numbers of products and their attributes. It will let you either update or create a product based on SKU. You would have to check the constants to see if they match your Magento.
This is a script for Community Edition so you would have to test for Enterprise.
<?php
include_once("app/Mage.php");
Mage::app();
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$counter = 0;
function GetProduct($sku)
{
global $counter;
echo $sku;
$p = Mage::getModel('catalog/product');
$productId = $p -> getIdBySku($sku);
if($productId)
{
echo "!";
$p -> load( $productId );
}
else
{
$p->setTypeId('simple');
$p->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$p->setStatus(1);
$p->setTaxClassId(7);
$p->setWebsiteIDs(array(1));
$p->setStoreIDs(array(1));
$p->setAttributeSetId(4);
$p->setSku($sku);
}
echo "...";
$counter++;
echo " ".$counter;
return $p;
}
function SaveProduct($p)
{
try
{
if (is_array($errors = $p->validate()))
{
$strErrors = array();
foreach($errors as $code=>$error)
{
$strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
echo $strErrors[0];
}
$this->_fault('data_invalid', implode("\n", $strErrors));
}
$p->save();
echo "\n";
}
catch (Mage_Core_Exception $e)
{
$this->_fault('data_invalid', $e->getMessage());
}
}
$product = GetProduct('SKU01'); $product->setData('upc', '013051388461'); SaveProduct($product); unset($product);
$product = GetProduct('SKU02'); $product->setData('special_price', null); $product->setData('special_from_date', null); SaveProduct($product); unset($product);
$product = GetProduct('SKU03'); $product->setData('cardboard_height_cm', 28.5); $product->setData('cardboard_width_cm', 37); SaveProduct($product); unset($product);
?>
I often get Excel to create the lines like $product = GetProduct('SKU03'); $product->setData('cardboard_height_cm', 28.5); $product->setData('cardboard_width_cm', 37); SaveProduct($product); unset($product); and then just copy and paste into the script. I can edit before running.
This is much faster than importing a CSV and it calls all of the correct observers.
Just run this from a SSH shell.
I have added the below code in my controller to add the product to wishlist programmatically. But whenever ajax request goes to the controller it replaces my previously added product from the wishlist and adds the new one to wishlist.
Can somebody please help with this.
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
// Load the customer's data
$customer = Mage::getSingleton('customer/session')->getCustomer();
//echo $customer->getName(); // Full Name
$customerId = $customer->getId(); // First Name
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
$product = Mage::getModel('catalog/product')->load($productId);
$result = $wishlist->addNewItem($product);
$wishlist->save();
echo "added to wishlist";
}
You can try below :
$product = Mage::getModel('catalog/product')->load($productId);
if (!$product->getId() || !$product->isVisibleInCatalog()) {
//$this->__('Cannot specify product.');
}
try {
$requestParams = $this->getRequest()->getParams();
$buyRequest = new Varien_Object($requestParams=array());
$result = $wishlist->addNewItem($product, $buyRequest);
if (is_string($result)) {
Mage::throwException($result);
}
$wishlist->save();
Mage::dispatchEvent(
'wishlist_add_product',
array(
'wishlist' => $wishlist,
'product' => $product,
'item' => $result
)
);
Mage::helper('wishlist')->calculate();
$message = $this->__('%1$s has been added to your wishlist. Click here to continue shopping.',
$product->getName(), Mage::helper('core')->escapeUrl($referer));
} catch (Mage_Core_Exception $e) {
echo $this->__('An error occurred while adding item to wishlist: %s', $e->getMessage());
}
catch (Exception $e) {
echo ($this->__('An error occurred while adding item to wishlist.'));
}
I try write this code
public function allsalesblock(){
echo 'other block ';
$orders = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getId());
->addAttributeToSort('created_at', 'DESC');
$order = Mage::getModel("sales/order")->load($orders); //load order by order id
$ordered_items = $order->getAllItems();
foreach($ordered_items as $item){
echo $item->getItemId(); //product id
echo $item->getSku();
echo $item->getQtyOrdered(); //ordered qty of item
echo $item->getName();
}
}
But this doesn't work - i see white screen. I found this code(and modification) here How can I display all products bought by a customer in magento?
You can get it using below code,
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$email = 'albert#example.com';
$_orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_email',$email);
foreach ($_orders as $order) {
$id[]= $order->getId();
}
//print_r($id);
foreach ($id as $order_id) {
$order = Mage::getModel('sales/order')->load($order_id);
#get all items
$items = $order->getAllItems();
$itemcount= count($items);
$data = array();
$i=0;
#loop for all order items
foreach ($items as $itemId => $item)
{
$data[$i]['name'] = $item->getName();
$data[$i]['price'] = $item->getPrice();
$data[$i]['sku'] = $item->getSku();
$data[$i]['id'] = $item->getProductId();
$data[$i]['qty'] = $item->getQtyToInvoice();
}
#displaying the array in order to see the products
echo '<pre/>';print_r($data);
}
here change the email address as you want to get products which that customer bought,
$email = 'albert#example.com';
Here is the standard code I am using for getting cart items and their attributes which works only when the customer is not logged in. As soon as I log in using my account this script stops working and does not return the items in the cart. Also the cart items count is also 0. But as soon as I close the browser(session ends..) and the script returns the cartitems correctly! Very strange, I have not been able to find out the cause. Please guide, anyone?
require_once('../app/Mage.php') ;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName(); //HERE IS THE COMPLETE CODE:<?php
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
//Getting buyer's country label
$bcountry1 = $_REQUEST['country']; //gets country code
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
foreach($_countries as $_country){
if ($_country['value']==$bcountry1){$bcountry = $_country['label'];}
}
//Fetching vendor for each product
$config = Mage::getConfig()->getResourceConnectionConfig("default_setup");
$dbinfo = array("host" => $config->host,
"user" => $config->username,
"pass" => $config->password,
"dbname" => $config->dbname );
$hostname = $dbinfo["host"];
$user2 = $dbinfo["user"];
$password = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
$dbhandle = mysql_connect($hostname,$user2,$password) or die("Unable to connect");
$selected = mysql_select_db("myart2",$dbhandle);
$Proceed=0;
//Getting all products in the cart
//echo $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
$productname = $item->getName();
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $item->getSku(), array('manufacturer'));
$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontEnd()->getValue($product);
$qry="select * from vendors WHERE company_name='$manufacturer'";
$result = mysql_query($qry) or die("Unable to run select query");
$row = mysql_fetch_array($result) or die("Unable to fetch data");
if( strcasecmp($row['country'],$bcountry)!=0 && $row['ships_abroad']!=1)
{$Proceed=1;$productnames[]=$productname;}
}
if($Proceed==1)
{
echo implode(',',$productnames);
}
else {echo 1; }
?>
I've tested the following four main permutations, and the code works in a stock CE1.7 instance in all cases:
Create guest quote
Convert guest quote to customer quote via login
Instantiate existing customer quote via login
Merge guest quote with customer quote via login
Adjust the server & app environment params as follows to view & rule out any errors (edit - added complete script; note the closing "}"):
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName();
}