1

I'm trying to add a product to cart programmatically in magento 1.9.3.3. The code adds database entries (created rows in sales_flat_quote_item and sales_flat_quote tables). But the cart shows as empty.

Here is my code

$cart = Mage::getSingleton('checkout/session')->getQuote();
$product = Mage::getModel('catalog/product')->load(1);
$cart->addProduct($product,1);
$cart->save();
Mage::getSingleton('customer/session')->setCartWasUpdated(true);            
Mage::getSingleton('core/session')->addSuccess('The product has been added to cart');
$this->_redirect('checkout/cart');

1 Answer 1

5
<?php
include 'app/Mage.php';

Mage::app();
ini_set('display_errors', 1);


Mage::getSingleton('core/session', array('name' => 'frontend'));
try {
    $product_id = '394'; // Replace id with your product id
    $qty = '1'; // Replace qty with your qty
    $product = Mage::getModel('catalog/product')->load($product_id);
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $cart->addProduct($product, array('qty' => $qty));
    $cart->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    Mage::getSingleton('core/session')->addSuccess('Product added successfully');
    header('Location: ' . 'checkout/cart/');
} catch (Exception $e) {
    echo $e->getMessage();
}
?>
3
  • try this and let me know the status. thanks
    – Raghu
    Commented Aug 9, 2017 at 6:09
  • It is not working. No tables were updated Commented Aug 9, 2017 at 6:28
  • its perfectly working for me here. Did you change the product Id?
    – Raghu
    Commented Aug 9, 2017 at 6:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.