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');

1 Answer 1

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
    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.