Here we have firstly truncate our magento cart,
$cart = Mage::getModel('checkout/cart');
$cart->truncate()->save(); // remove all active items in cart page
$cart->init();
Mage::getSingleton('checkout/session')->clear();
After this, we tried to add products
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$cart->addProduct($id,$qty);
Its giving 500 Internal Server Error
Note: Its only giving error when we apply adding product quantity to max.
Ex. available qty. 100
here in my case $qty=100
Editedcode :
<?php
include 'app/Mage.php';
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));
// Need for start the session
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
echo count($items);
foreach($items as $item)
{
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
}
try {
$product_id = '7896'; // Replace id with your product id
$qty = '99'; // max 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);
} catch (Exception $e) {
echo $e->getMessage();
}
Note : Our code is working perfectly for first time only, rest of all time its giving this error
Kindly help