Jump to content

Recommended Posts

I've been working on the delete item from cart functionality all day. Still cannot figure this out.

 

When I add 2+ items to my cart, and try to delete any item but the last item added, the script deletes the listing the last item added no matter which one I'm attempting to delete. I could do this in C++ but the php solution is evading me. This has frustrated me today for over 4 hours just this one little problem. Can somebody please shine light on this for me, to help me see why I'm so close to finishing the delete functionality but it won't quite work. Here's my code:

 

header.html (included in cart at top):

session_start();

// For personal debugging -- REMOVE WHEN DONE //
if ($_GET['des']) {
	session_destroy();
	unset($_GET['des']);
}

// ---- //

// Count Cart Items //
if (empty($_SESSION['count_cart'])) {
	$_SESSION['count_cart'] = 0;
}

// Handle Delete Item //
if ($_POST['submitted']) {
	$_SESSION['count_cart']--;
	$delItem = $_POST['delItem'];
	unset($_SESSION['item'][$delItem]);
	unset($_POST['submitted']);
}

// Handle setting sessions //
if ($_POST['name'] == $PHPSESSID && isset($_POST['mdl_key'])) {
	$idx = $_SESSION['count_cart'];
	$_SESSION['count_cart']++;
	$_SESSION['item'][$idx][0] = $_POST['mdl_key'];
	$_SESSION['item'][$idx][1] = $_POST['model'];
	$_SESSION['item'][$idx][2] = $_POST['manufacturer'];
	$_SESSION['item'][$idx][3] = $_POST['sellprice'];
	$_SESSION['uri'][$idx] = $_POST['uri'];
}

And here is the code for the shoppingcart_customer.php page where the above is included with include:

<form name="del" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$i=0;
$count = $i + 1;
foreach ($_SESSION['item'] as $key=>$v1) { 
	if (isset($_SESSION['item'][$key])) {
		echo "<tr><td width='30px'></td><td bgcolor='white'>".$count.".) ";
		foreach ($v1 as $v2){
	    	echo $v2." ";
	    }
	}
echo " - <a href='".$_SESSION['uri'][$i]."' target='_blank'>View Details</a> | 
<input type='submit' value='Delete' name='delete'/>
<input type='hidden' name='delItem' value='".$i."'/>
<input type='hidden' name='submitted' value='TRUE'/>
</td><td width='80px'></td></tr>";
$i++;
}
?>
</form>

 

and here is the html $_POST code:

<form enctype="multipart/form-data" action="shoppingcart-customer.php" method="post">
<input type="hidden" name="name" value="<?php echo $PHPSESSID; ?>"/>
<input type="hidden" name="mdl_key" value="<?php echo $mdl_key; ?>"/>
<input type="hidden" name="model" value="<?php echo $model; ?>"/>
<input type="hidden" name="manufacturer" value="<?php echo $manufacturer; ?>"/>
<input type="hidden" name="sellprice" value="<?php echo $sellprice; ?>"/>
<input type="hidden" name="uri" value="<?php echo $_SERVER['REQUEST_URI']; ?>"/>
<input type="submit" name="addtocart" value="Add To Cart" id="hyperlink-style-button"/>
	</form>
Edited by rcast
Link to comment
https://forums.phpfreaks.com/topic/276066-help-with-arrays-and-sessions/
Share on other sites

Great this helped me fix that problem. However now say I have added 3 items to cart:

 

List after added 3 items to cart

Item 1 - (DELETE)

Item 2

Item 3

 

New list generated after item 1 deleted:

Item 1 (array element 1 instead of array element 0, became item 1, throwing off the entire array)

Item 2

 

So basically, following the above example, after I delete item 1 from the cart my array looks like this:

$_SESSION['item'][0][0] = EMPTY   < -------------- Need to reorder so the two elements below this fill the empty spot

$_SESSION['item'][1][0] = Correct

$_SESSION['item'][2][0] = Correct

 

I'm guessing I need to resort the array moving each array element's items down one index, within the delete function code - How would I do this?

Edited by rcast

this is just my opinion, but the defintion of your cart is resulting in extra code and data, and even results in security problems because you are passing unneeded data through the form that must be validated once it reaches the server.

 

your cart should use the item id from the product database as the first level key and the only real data you need to store in the cart for each item is the quantity. the only thing the add to cart form needs to submit is the item id and a quantity (assuming you want to allow more than one of anything to be bought.) to delete the item from the cart, just use the item id to unset it like you are doing now. there's no need to move or renumber the indexes.

 

what's with the $_SESSION['count_cart']? you can just use the php array count() function to get a count of the items in the cart at any time or if you are storing a quantity of each item, use array_sum(). no need for any extra code to set the count_cart variable or to increment and decerment it.

 

to display the cart, just get all the item ids out of the cart and use them to fetch the display information from the database.

code snippets that implement the suggestions -

<?php
session_start();

// simple form process controller -
$action = isset($_POST['action']) ? $_POST['action'] : '';
switch($action){
    case 'add':
        // add/increment item to cart (quantity one)
        // inputs: 'add to cart' flag, item id
        // processing: add new or increment existing item id in the cart
        $id = (int)$_POST['id'];
        if($id > 0){ // valid submitted id
            if(!isset($_SESSION['item'][$id])){ // not already in cart
                $_SESSION['item'][$id] = 0; // create entry
            }
            $_SESSION['item'][$id]++; // increment quantity
        }
    break;
    case 'delete':
        // delete item from cart
        // inputs: 'delete from cart' flag, item id
        // processing: remove item id entry from the cart
        $id = (int)$_POST['id'];
        if($id > 0){ // valid submitted id
            unset($_SESSION['item'][$id]);
        }
    break;
}


// display the cart
if(empty($_SESSION['item'])){
    echo "Your cart is empty!<br>";
} else {
    echo "Your cart has ".array_sum($_SESSION['item'])." item(s) in it.<br>";

    // get the item ids from the cart
    $ids = implode(',',array_keys($_SESSION['item']));
    echo "ids are: $ids<br>";
    // code to get and display the product infomration for the list of ids is left as a programming exercise
}

// display what's going on
echo '<pre>','cart:',print_r($_SESSION,true),'post:',print_r($_POST,true),'</pre>';

?>
Add some items -<br>
id: 123<form method='post' action=''>
<input type='hidden' name='action' value='add'>
<input type='hidden' name='id' value='123'>
<input type='submit' value='Add to cart'>
</form>

id: 456<form method='post' action=''>
<input type='hidden' name='action' value='add'>
<input type='hidden' name='id' value='456'>
<input type='submit' value='Add to cart'>
</form>

Delete some items -<br>
id: 123<form method='post' action=''>
<input type='hidden' name='action' value='delete'>
<input type='hidden' name='id' value='123'>
<input type='submit' value='Remove from cart'>
</form>

id: 456<form method='post' action=''>
<input type='hidden' name='action' value='delete'>
<input type='hidden' name='id' value='456'>
<input type='submit' value='Remove from cart'>
</form>
 

This is something I put together:

 

<?PHP

  //### Start the session
  session_start();
 
  //### File name
  $filename = basename($_SERVER['PHP_SELF']);
 
  //### Assign $_GET variables if they exist
  $itemID    = isset($_GET['id']) ? (int)$_GET['id'] : FALSE ;
  $action    = isset($_GET['action']) ? $_GET['action'] : FALSE ;
  $subAction = isset($_GET['sub_action']) ? $_GET['sub_action'] : FALSE ;

  //### Add item to the items array, if it doesn't already exist
  if($action == 'add') {
    if(!isset($_SESSION['cart']['items'][$itemID])) {
      $_SESSION['cart']['items'][$itemID] = 1;
    }
    header('Location: '. $filename);
    exit;
  }
 
  //### Increase item count, if the item exists
  //### Decrease item count, if the item exists
  //### If the item count equals 1, remove the item from the item array
  if($action == 'update') {
    if($subAction == 'add') {
      if(isset($_SESSION['cart']['items'][$itemID])) {
        $_SESSION['cart']['items'][$itemID]++;
      }
    } else if($subAction == 'remove') {
      if(isset($_SESSION['cart']['items'][$itemID])) {
        if($_SESSION['cart']['items'][$itemID] > 1) {
          $_SESSION['cart']['items'][$itemID]--;    
        } else {
          header('Location: '. $filename .'?action=delete&sub_action=item&id='. $itemID);
          exit;
        }
      }
    }
    header('Location: '. $filename);
    exit;
  }  
 
  //### Delete item from item array, if it exists
  //### Delete all items from item array
  if($action == 'delete') {
    if($subAction == 'item') {
      if(isset($_SESSION['cart']['items'][$itemID])) {
        unset($_SESSION['cart']['items'][$itemID]);    
      }
    } else if($subAction == 'cart') {
      $_SESSION['cart']['items'] = array();   
    }
    header('Location: '. $filename);
    exit;
  }
 
  echo '<pre>';
  print_r($_SESSION);
  echo '</pre>';
 
  for($i=1; $i<=5; $i++) {
    echo '<a href="?action=add&id='.$i.'">Add Item '.$i.'</a> - ';
    echo '<a href="?action=update&sub_action=add&id='.$i.'">Update Item '.$i.'</a> - ';
    echo '<a href="?action=update&sub_action=remove&id='.$i.'">Remove Item '.$i.'</a> - ';
    echo '<a href="?action=delete&sub_action=item&id='.$i.'">Delete Item '.$i.'</a>';
    
    echo '<br>';
  }
 
  echo '<a href="?action=delete&sub_action=cart">Delete Cart</a>';
 
?>
Edited by PaulRyan
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.