Jump to content

Problem Reducing Shopping Basket Quantity By 1


stevesimo

Recommended Posts

Hi, I am trying to use some code which I have found in a tutorial to write my first shopping cart in PHP.

 

The code has an example to delete an item from the basket or to add an item to the basket.  However the code doesnt explain how to reduce a quantity in basket by 1.

 

Here is the code to delete an item from the basket

 

if ($cart) {

  $items = explode(',',$cart);

  $newcart = '';

  foreach ($items as $item) {

    if ($_GET['id'] != $item) {

      if ($newcart != '') {

        $newcart .= ','.$item;

      } else {

        $newcart = $item;

      }

    }

  }

$cart = $newcart;

}

 

Can anyone see what I need to do to reduce the quantity by 1.  Also How would I prevent the problem of somebody trying to reduce a quantity if it is already 0?

Link to comment
Share on other sites

Hi, I have discovered that the cart contains a comma seperated list of product ids.  So for example the cart 1,2,3,1,1,2 contains 3 of product 1, 2 of product 2, and 1 of product 3.  Providing I know what the product id is and that the quantity is greater than 0, how would I reduce the string by 1?

Link to comment
Share on other sites

Fixed it using a long winded approach.

 

//do a count of all items in the trolley

  if ($cart){

    $items = explode(',',$cart);

    $contents = array();

    foreach ($items as $item) {

      $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;

    }

  }

  //initialise empty cart

  $tempcart = "";

  //for each product in list

  foreach ($contents as $id=>$qty){

  //is product in list equal to one being reduced

  if($id == $_GET['id'] && $qty > 0){

    for($i=1;$i<$qty;$i++)

      //add all items - 1

      $tempcart = $tempcart.$id.',';

    }else{

      for($i=1;$i<=$qty;$i++)

      //add all items

      $tempcart = $tempcart.$id.',';

  }

  //trim final comma

  $cartlength = strlen($tempcart) - 1;

  $tempcart = substr($tempcart,0,$cartlength);

}

//set cart to tempcart

$cart = $tempcart;

 

Thanks for your help

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.