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');
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();
}
?>
  • try this and let me know the status. thanks – Raghu Aug 9 '17 at 6:09
  • It is not working. No tables were updated – Jancy Abraham Aug 9 '17 at 6:28
  • its perfectly working for me here. Did you change the product Id? – Raghu Aug 9 '17 at 6:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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