Solved

How to delete an item from shopping cart?

Posted on 2011-09-28
21
547 Views
Last Modified: 2012-05-12
Hi,

I would like to delete an item from the shopping cart but the it doesn't work.

Here is the item:


<td align=\"center\"> <input type=\"submit\" value=\"Remove\" name=\"delete[b3]\" class=\"submit\">


and the the function:

function removeItem() {
    if(isset($_POST['delete']) ) {
        foreach($_POST['delete'] as $item =>$v ) {
            $item = trim(mysql_clean_strings($item));
            unset($_SESSION['cart'][$item]);
            }
    }
}

Open in new window


Thanks!
0
Comment
Question by:hmbargi
  • 9
  • 5
  • 3
  • +2
21 Comments
 
LVL 26

Expert Comment

by:EddieShipman
ID: 36798643
Need more info. How are your items shown on the page in the form you are submitting?
0
 

Author Comment

by:hmbargi
ID: 36801945
Here is the function for displaying the items in the cart:

function display_cart($cart, $change = true, $images = 1) {
  // display items in shopping cart
  // optionally allow changes (true or false)
  // optionally include images (1 - yes, 0 - no)

   echo "<table border=\"0\" width=\"100%\" cellspacing=\"0\">
         <form action=\"show_cart.php\" method=\"post\">
         <tr><th colspan=\"".(1 + $images)."\" bgcolor=\"#cccccc\">Item</th>
         <th bgcolor=\"#cccccc\">Price</th>
         <th bgcolor=\"#cccccc\">Quantity</th>
         <th bgcolor=\"#cccccc\">Total</th>
         <th bgcolor=\"#cccccc\">Remove</th>
         </tr>";

  //display each item as a table row
  foreach ($cart as $itemid => $qty)  {
    $item = get_item_details($itemid);
    echo "<tr>";
    if($images == true) {
      echo "<td align=\"left\">";
      if (file_exists("images/".$itemid.".jpg")) {
         $size = GetImageSize("images/".$itemid.".jpg");
         if(($size[0] > 0) && ($size[1] > 0)) {
           echo "<img src=\"images/".$itemid.".jpg\"
                  style=\"border: 1px solid black\"
                  width=\"".($size[0]/3)."\"
                  height=\"".($size[1]/3)."\"/>";
         }
      } else {
         echo "&nbsp;";
      }
      echo "</td>";
    }
    echo "<td align=\"left\">
          <a href=\"show_item.php?itemid=".$itemid."\">".$item['name']."</a>
          </td>
          <td align=\"center\">\$".number_format($item['price'], 2)."</td>
                          

          <td align=\"center\">";

    // if we allow changes, quantities are in text boxes
    if ($change == true) {
      echo "<input type=\"text\" name=\"".$itemid."\" value=\"".$qty."\" size=\"3\">";
    } else {
      echo $qty;
    }
    echo "</td><td align=\"center\">\$".number_format($item['price']*$qty,2)."</td>
        
  
         <td align=\"center\"> <input type=\"submit\" value=\"Remove\" name=\"delete[b3]\" class=\"submit\">
         
        </td>
            </tr>\n";
  }
  // display total row
  echo "<tr>
        <th colspan=\"".(2+$images)."\" bgcolor=\"#cccccc\">&nbsp;</td>
        <th align=\"center\" bgcolor=\"#cccccc\">".$_SESSION['items']."</th>
        <th align=\"center\" bgcolor=\"#cccccc\">
            \$".number_format($_SESSION['total_price'], 2)."
        </th>
        <th align=\"center\" bgcolor=\"#cccccc\"></th>
        </tr>";

  // display save change button
  if($change == true) {
    echo "<tr>
          <td colspan=\"".(2+$images)."\">&nbsp;</td>
          <td align=\"center\">
             <input type=\"hidden\" name=\"save\" value=\"true\"/>
             <input type=\"image\" src=\"images/save-changes.gif\"
                    border=\"0\" alt=\"Save Changes\"/>
          </td>
          <td>&nbsp;</td>
          </tr>";
  }
  echo "</form></table>";
}

Open in new window

0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36810857
Any relevant error messages in the http server's log file?

I suggest a var_dump of all the variables you are using ( $_POST, $_SESSION ...).  I would look at $item before and after trimming.

You are looking for anything that surprises you.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36813901
What is the shopping cart that you are using?  I don't recognize the code.
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 36814181
Need to also see code for show_cart.php to see how the delete is handled.
0
 

Author Comment

by:hmbargi
ID: 36814249
hmccurdy: changing the variable doesn't work.

Ray_Paseur: Don't know what do you mean.

EddieShipman: Here is the shoe_cart.php code

<?php
  include ('hbargi_fns.php');
  // The shopping cart needs sessions, so start one
  session_start();

  @$new = $_GET['new'];

  if($new) {
    //new item selected
    if(!isset($_SESSION['cart'])) {
      $_SESSION['cart'] = array();
      $_SESSION['items'] = 0;
      $_SESSION['total_price'] ='0.00';
    }

    if(isset($_SESSION['cart'][$new])) {
      $_SESSION['cart'][$new]++;
    } else {
      $_SESSION['cart'][$new] = 1;
    }

    $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    $_SESSION['items'] = calculate_items($_SESSION['cart']);
  }

  if(isset($_POST['save'])) {
    foreach ($_SESSION['cart'] as $itemid => $qty) {
      if($_POST[$itemid] == '0') {
        unset($_SESSION['cart'][$itemid]);
      } else {
        $_SESSION['cart'][$itemid] = $_POST[$itemid];
      }
    }

    $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    $_SESSION['items'] = calculate_items($_SESSION['cart']);
  }

  do_html_header("Your shopping cart");
  

  if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
    display_cart($_SESSION['cart']);
  } else {
    echo "<p>There are no items in your cart</p><hr/>";
  }
  
   // get the item info out from
  
  $target = "index.php";

  // if we have just added an item to the cart, continue shopping in that country
  if($new)   {
    $details =  get_item_details($new);
    if($details['catid']) {
      $target = "show_cat.php?catid=".$details['catid'];
    }
  }
  display_button($target, "continue-shopping", "Continue Shopping");

  // use this if SSL is set up
  // $path = $_SERVER['PHP_SELF'];
  // $server = $_SERVER['SERVER_NAME'];
  // $path = str_replace('show_cart.php', '', $path);
  // display_button("https://".$server.$path."checkout.php",
  //                 "go-to-checkout", "Go To Checkout");

  // if no SSL use below code
  display_button("checkout.php", "go-to-checkout", "Go To Checkout");

  do_html_footer();
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36814279
What is the shopping cart that you are using?  By that I mean, what is the name of the shopping cart.  Like Magento, UberCart, etc.
0
 

Author Comment

by:hmbargi
ID: 36814377
I'm not using any outsource shopping cart. I'm building my own cart.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 36814408
The POST array as if you are submitting it contains nothing. the name for the submit does not post the b3 value to the target form. Do you have any other input fields that have values ?
0
 

Author Comment

by:hmbargi
ID: 36814536
Since I'm newbie to php, do I have to include some code to show_cart.php or just deal with submit button and create a function that calls it.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 36814574
Since you are a newbie, I'd recommend doing it step by step with a simple tutorial - having a ready made functions may be a little confusing at this point, build it by yourself, you'll learn a lot.

http://v3.thewatchmakerproject.com/journal/276/
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36814708
I wasn't trying to get you to change the variables.  I want you to print them out and share any answers that don't make sense to you.

0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 36814744
I don't see that you are handling the delete submit button in the show_cart.php file at all. Try something like this:
  // Handle deleting the item
  if(isset($_POST['delete[b3]'])) {
    removeItem($_SESSION['cart'][$item); // Then modify the removeItem function to take the item as a parameter
  }

  do_html_header("Your shopping cart");

Open in new window

0
 

Author Comment

by:hmbargi
ID: 36815361
EddieShipman: Tried your code. Doesn't work!
0
 

Author Comment

by:hmbargi
ID: 36815407
Do I have to create a table in DB for the items in the cart?
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36815921
Do I have to create a table in DB for the items in the cart?

No.  But I strongly suggest that you do.
0
 

Author Comment

by:hmbargi
ID: 36818704
Still need help guys.
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36818908
What approach do you want to take?  Are you going to go with my suggestion and add the cart to a DB or do you want to stick with session variables?
0
 

Author Comment

by:hmbargi
ID: 36819057
Either ways fine with me. I created the order_items table but still couldn't figure out how to implement the code.
0
 
LVL 13

Accepted Solution

by:
Hugh McCurdy earned 400 total points
ID: 36862970
I would make the table so that each item in the shopping cart is a row in the table.  Each line item would then have its on record ID (first column).  Another column would be a customer identifier.  You can select all items by customer ID for when a customer returns.  You can put the record ID as a hidden variable on the shopping cart form.

If the customer wants to delete line 3 of his shopping cart, you would know the record number number and delete WHERE RecordID = '1234';  (for example)

You can also delete a customer's entire cart... WHERE CustID = "ABCD";

Does this make sense (at least as an overall design)?
0
 

Author Closing Comment

by:hmbargi
ID: 36890703
Not what I expected. I got a provided a code so Nobody was able to fix it.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now