简体   繁体   中英

Removing Items in Session Array

I've been wracking my brains for for three days and still can't find the solution to my problem of removing items from a session array.

I'm learning PHP and how to build a shopping cart; I know that there are frameworks but I really want to learn programming, solve problems and create things.

My problem is this: Say I placed three items in the cart...

  1. Cookies
  2. Donuts
  3. Cupcakes

When I delete an item in the shopping cart, everything else down the list (below that item) is deleted as well. If remove DONUTS, Cupcakes is removed as well. If I remove Cookies, the whole list is removed/cleared

But if I start from the bottom (Cookies) going up the list, it works fine; it will only remove the one I clicked.

Here's my code along with other attempts. Not styled yet, just working on logic.

 <?php

session_start();

$prodid = $_POST['prodid'];
$quantity = $_POST['quantity'];
$empty= $_POST['empty']; 
$removed = $_POST['remove'];

   if (isset($empty ))
    {
    unset($_SESSION['shop_cart']);
    }


if (!isset($_SESSION['shop_cart']))//Checking if Session is Set or empty
   {
      unset($_SESSION['shop_cart']);
      echo "Cart is empty";
   } else
   {
      if(count($_SESSION['shop_cart'])==NULL || count($_SESSION['shop_cart'])==0 )
      {
         echo "Cart is empty";
      }
   }



/////// THIS IS THE SECTION THAT I'VE BEEN FIDDLING WITH --Am I on the right track
    if (isset($removed))  
    {
    foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
       {
        if($prodid==$item['prodid'])
            {
            unset($_SESSION['shop_cart'][$cart_line_item]); ///9:47pm May 20, 2013 
            break;
            }   
        }
    }
///////////////////////////////////////////////////////////////////////////////////


//Check if item is already in cart 
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
    {
    if ($item['prodid']==$prodid)
        {
        $quantity=0;
    echo "In Cart Already <br/>";
        break;           
        }
    }

$cap=count($_SESSION['shop_cart']);
$_SESSION['shop_cart'][$cap]['prodid']=$prodid;
$_SESSION['shop_cart'][$cap]['quantity']=$quantity;
$_SESSION['shop_cart'][$cap]['description']=$description;

//Prevent Items with zero quantity
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
    {
    if ($item['quantity'] == 0 || $item['quantity'] == NULL)
        {
        unset($_SESSION['shop_cart'][$cart_line_item]);
        break;
        }
    }    


$total=0; //For Price

 if (isset($_SESSION['shop_cart']))  
  {
    for($i=0;$i<count($_SESSION['shop_cart']);$i++)
    {
        $prodid=$_SESSION['shop_cart'][$i]['prodid'];
        $quantity=$_SESSION['shop_cart'][$i]['quantity'];
        $description=$_SESSION['shop_cart'][$i]['description'];

        $query = "SELECT prodid, description, price FROM products WHERE prodid = $prodid";
        $result = mysqli_query($hook, $query);
        $row = mysqli_fetch_assoc($result);

        $prodid = $row['prodid'];
        $price = $row['price'];
        $description= $row['description'];

        $subtotal = $price * $quantity;
                    $total += $subtotal;

echo "$description($prodid)---Quantity: $quantity--- $$price";      

echo "<form action=\"$_SERVER[SCRIPT_NAME]\" method=\"post\" >";
echo "<INPUT TYPE=\"submit\" name=\"remove\" VALUE=\"Remove\">";
echo "<input type=\"hidden\" name=\"prodid\" value=$prodid />\n";
echo "<input type=\"hidden\" name=\"counter\" value=\"$i\"/>\n"; 
echo "</FORM>";

echo "--------------------------<br/><br/>";

    }                                                             
  }

echo "TOTAL $total <br/><br/>";

echo '<pre>'. var_dump( $_SESSION['shop_cart']).'<pre/>';

echo "<br/>";

echo "<form action=\"$_SERVER[SCRIPT_NAME]\" method=\"post\" >";
echo "<INPUT TYPE=\"submit\" name=\"empty\" VALUE=\"Empty Cart \">";
echo "</FORM>";

?> 

These versions of that section of code yield the same result

A.

$counter= $_POST['counter'];
echo "COUNTER $counter";

    if (isset($removed))
    {   
    unset($_SESSION['shop_cart'][$counter]);  
    continue;
    }

B.

if (isset($removed))
for($i=0;$i<count($_SESSION['shop_cart']);$i++)
    if($prodid==$_SESSION['shop_cart'][$i]['prodid'])
        {
         $_SESSION['shop_cart'][$i]=$quantity==0; 
          continue;
        }

C.

if (isset($removed))
for($i=0;$i<count($_SESSION['shop_cart']);$i++)
    if($prodid==$_SESSION['shop_cart'][$i]['prodid'])
      {
        unset($_SESSION['shop_cart'][$i]['prodid']); 
    //OR
        //unset($_SESSION['shop_cart'][$i]);  
        continue;
        }

This doesn't work at all

if (isset($removed))
{
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
       {

        if($prodid==$item['prodid'])
            {
            unset($_SESSION['shop_cart']['prodid']);
            unset($_SESSION['shop_cart']['quantity']);
            unset($_SESSION['shop_cart']['description']);           
            continue;
            }    
}
}

For @Soyale:

Is this what you mean?:

if (isset($removed))  
{
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
   {
    if($prodid==$item['prodid'])
        {
        unset($_SESSION['shop_cart'][$cart_line_item]);
        continue;
        }   
    }
}

Same result.

Your problem lies here:

    for($i=0;$i<count($_SESSION['shop_cart']);$i++)
    {
        $prodid=$_SESSION['shop_cart'][$i]['prodid'];
        $quantity=$_SESSION['shop_cart'][$i]['quantity'];
        $description=$_SESSION['shop_cart'][$i]['description'];

        $query = "SELECT prodid, description, price FROM products WHERE prodid = $prodid";
        $result = mysqli_query($hook, $query);
        $row = mysqli_fetch_assoc($result);

        $prodid = $row['prodid'];
        $price = $row['price'];
        $description= $row['description'];

        $subtotal = $price * $quantity;
                    $total += $subtotal;

echo "$description($prodid)---Quantity: $quantity--- $$price";      

echo "<form action=\"$_SERVER[SCRIPT_NAME]\" method=\"post\" >";
echo "<INPUT TYPE=\"submit\" name=\"remove\" VALUE=\"Remove\">";
echo "<input type=\"hidden\" name=\"prodid\" value=$prodid />\n";
echo "<input type=\"hidden\" name=\"counter\" value=\"$i\"/>\n"; 
echo "</FORM>";

echo "--------------------------<br/><br/>";

    }                                                             
  }

You shuld use foreach instead for. Why? Because the keys were deleted when you use unset. Basic array ie

array (size=2)
  0 => 
    array (size=3)
      'prodid' => string '1' (length=1)
      'quantity' => string '2' (length=1)
      'description' => null
  1 => 
    array (size=3)
      'prodid' => string '2' (length=1)
      'quantity' => string '2' (length=1)
      'description' => null
  2 => 
    array (size=3)
      'prodid' => string '3' (length=1)
      'quantity' => string '2' (length=1)
      'description' => null

After deleting product with prodid=2 will look like this:

array (size=2)
  0 => 
    array (size=3)
      'prodid' => string '1' (length=1)
      'quantity' => string '2' (length=1)
      'description' => null
  2 => 
    array (size=3)
      'prodid' => string '3' (length=1)
      'quantity' => string '2' (length=1)
      'description' => null

Length of the final table is 2. When you use something like this for($i=0;$i<count($_SESSION['shop_cart']);$i++) then second product will newer be displayed (because keys). Even more there isn't row with index 1 so the empy row will be placed there.

Look at this lines:

$total=0; //For Price

 if (isset($_SESSION['shop_cart']))  
  {
    for($i=0;$i<count($_SESSION['shop_cart']);$i++) //-> this is a bad idea please change this to foreach
    {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM