I'm trying to add a product to cart programmatically in magento 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);
Mage::getSingleton('core/session')->addSuccess('The product has been added to cart');
include 'app/Mage.php';

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->addProduct($product, array('qty' => $qty));
    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 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.