0

This is kind of in conjunction to my first post, but new issue. I wasn't sure the protocol so I created a new topic. (link to first post)

I have searched around on here and found a couple different instances of my issue but cannot seem to understand anything enough to move forward with my own program.

Brief description: Shopping cart. I have a few items listed on a page with an itemID. The user clicks on an item, it gets added to the cart. If the user clicks the same item twice, the quantity should increment by one (currently hard coded). The $_SESSION['cart'] array should start empty and be dynamic.

Current issues: In testing it seems to only loop through the array once, array_push gives error even though parameter one is an array, does not remove an item as it should, and is not reading the quantity in the for loop. It displays '1' in print_r($_SESSION['cart'] but '0' in $_SESSION['cart']['itemID']['quantity'];

Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\A06_DictCart\controller\updateCart.php on line 25

Kind of a few different issues I suppose, but fixing one will help me move forward with the others, I would imagine they are semi-related.

viewCart.php

<?php
session_start();

/* Display the itemID and quantity of each item in the shopping cart.
This may be implemented by iterating though the items in the dictionary 
and displaying their keys and values. */
echo ' ** array/ '.print_r($_SESSION['cart']).' ** count/ '.count($_SESSION['cart']);
echo '<br>'.$_SESSION['cart']['itemID']['quantity'];
echo '<center><h2><u>SHOPPING CART</u></h2>';
echo '<br><TABLE border=1 cellPadding=3 cellSpacing=1>
        <TBODY>
        <TR>
          <TD>ItemID</TD>
          <TD>Quantity</TD>
          <TD>Remove from Cart</TD></TR>';

if (isset($_SESSION['cart'])) {
    $c = count($_SESSION['cart']);
    for ($x=0; $x <= $c; $x++){
        echo '<tr><td>'.$_SESSION['cart']['itemID'].'</td>';
        echo '<td>'.$_SESSION['cart']['itemID']['quantity'].'</td>';
        echo "<td><a href='updateCart.php?action=remove&amp;itemID=".$_SESSION['cart']['itemID']."&amp;quantity=".$qty."> Remove from Cart </a></td></tr>";
        $x++;
    }   
}
else {
    $msg = '<i> ** cart is empty ** </i>';
    echo '<tr> <td></td>';
    echo '<td> </td>';
    echo "<td> </td></tr>";
}

echo '</tbody></table>';
echo $msg;
echo '<br><br><a href="../controller/default.php">Back to Catalog</a>';
echo '<br><a href="../controller/updateCart.php?action=clear">Empty Cart</a></center>';
?>

updateCart.php

<?php
/* Read the values of action, itemID, and quantity from the querystring.  
Items will either be added or removed from the shopping cart depending 
on the values of the querystring. Once the quantity is 0 the item should 
be unset from the cart. */

session_start();

$action = $_GET['action'];
$itemID = $_GET['itemID'];
$qty = $_GET['quantity'];
$msg;

if (empty($_SESSION['cart'])) $_SESSION['cart'] = array();
//array(); //('123' => 0, '456' => 0, '789' => 0, '101' => 0);
//$cart = array($_SESSION['cart']);

// ADD TO CART
if ($action == 'add') { 
    if (!in_array($itemID, $_SESSION['cart'])) {    
        $_SESSION['cart']= array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item
    } else {
        $temp = array($_SESSION['cart']);
        $q += $_SESSION['cart'][$itemID]['qty'];
        $temp = array('itemID' => $itemID, 'quantity' => $q);
        array_push($_SESSION['cart'][$itemID], $temp);// Update existing item's quantity
    }
    $msg = $qty.' of item # '.$itemID.' has been added to your cart.';
}
// REMOVE FROM CART
if ($action == 'remove'){ 
    if (($_SESSION['cart'][$itemID]['quantity'] - 1) <= 0)
        unset ($_SESSION['cart'][$itemID]); // If new value is zero, unset elements
    else
        $_SESSION['cart'][$itemID]['quantity']--;   // Else decrease quantity by one
    $msg = $qty.' of item # '.$itemID.' has been removed to your cart.';
}
// EMPTY CART
if ($action == 'clear') { 
    unset($_SESSION['cart']);   // Unset session
    session_destroy();  
    $msg = 'Your shopping cart has been emptied.';
}

?>


<HTML>
    <HEAD>
    </HEAD>
<BODY>
<center>
    <p> <?php echo $msg; ?><br><br>
    <p><a href="../controller/default.php">Back to Catalog</a></p>
    <p><a href="../controller/viewCart.php">View Cart</a></p>
</center>
</BODY>
</HTML>

Being that this is a work-in-progress there may be some discrepancies in the code syntax-wise that I have not discovered yet. Some of the code in the 'remove from cart' statement I saw in another post.

Any help is appreciated.

mallorz
  • 55
  • 1
  • 8

2 Answers2

0

I did not test this, but try this code:

// ADD TO CART
if ($action == 'add') { 
    if (!isset($_SESSION['cart'][$itemID])) {    
        $_SESSION['cart'][$itemID] = array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item
    } else {
        $_SESSION['cart'][$itemID]['quantity'] += $qty     
    }
    $msg = $qty.' of item # '.$itemID.' has been added to your cart.';
}

That is how I would write this. I suppose in your code

$_SESSION['cart']= array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item

should be

$_SESSION['cart'][$itemID] = array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item

And I think you mixed up 'qty' with your 'quantity' key in your original code. On update you read on the key qty but your initaliser had quantity as the key:

$q += $_SESSION['cart'][$itemID]['qty'];

might be supposed to be written as

$q += $_SESSION['cart'][$itemID]['quantity'];

EDIT: Note this Image

Nibbels
  • 156
  • 10
  • Thanks - that was definitely some of it! Variables are being added to the array now, both ID and quantity. Somewhere along the way my viewCart seems to have been affected. I'll keep playing. – mallorz Oct 03 '15 at 22:27
  • nice :) have fun! And look into this short codingstyle I suggested for your keys.. $array[key][subkey][subsubkey]. For the future: If you destroy a session just because you want to delete one array, you might wanna use `$_SESSION['cart'] = array();` there as well. otherwise you could delete future status-things accidently. I would be flawed if you could vote up my answer - i need 50 points to comment another thread :D – Nibbels Oct 03 '15 at 22:34
  • Am I calling the quantity wrong in the for loop? No matter what I do it prints '0' but I can see it is '1' in the array. – mallorz Oct 03 '15 at 23:13
  • Maybe see this Image: [link](http://i.imgur.com/yVm4IBE.png) I did mark the flaws I see within it. – Nibbels Oct 03 '15 at 23:20
  • Btw: This line: ´$temp = array($_SESSION['cart']);´ is not making any sense to me. I would remove it, if you still work with your old code – Nibbels Oct 03 '15 at 23:29
  • I have. It was more of a troubleshooting type of thing, trying different methods to get where I need to be. Consider it a "shot in the dark" approach. – mallorz Oct 03 '15 at 23:35
0

You might want to think about the logic of your app and what you are trying to achieve before you start writing any code.

if ($action == 'add') { 
  if (!in_array($itemID, $_SESSION['cart'])) {    
    $_SESSION['cart']= array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item
  } else {
    $temp = array($_SESSION['cart']);
    $q += $_SESSION['cart'][$itemID]['qty'];
    $temp = array('itemID' => $itemID, 'quantity' => $q);
    array_push($_SESSION['cart'][$itemID], $temp);// Update existing item's quantity
  }
}

Should simply be:

if ($action == 'add' ) {
   $_SESSION['cart'][$itemID]+=$qty;
}

(Note the change to the array structure)

symcbean
  • 47,736
  • 6
  • 59
  • 94