0

I have the following function in PHP which adds an item to a shopping cart every time the user clicks on Add to cart.

The issue is that, if someone reloads manually the page after having added an item to the cart, a new item gets added.

Any tips to avoid this?

function addtocart($pid,$q)
    {
        if($pid<1 or $q<1) return;
        if(is_array($_SESSION['cart']))
        {

            $max=count($_SESSION['cart']);
            $_SESSION['cart'][$max]['itemId']=$pid;
            $_SESSION['cart'][$max]['qty']=$q;
            $max=count($_SESSION['cart']);
        }
        else
        {
            $_SESSION['cart']=array();
            $_SESSION['cart'][0]['itemId']=$pid;
            $_SESSION['cart'][0]['qty']=$q;
            $max=count($_SESSION['cart']);

        }
    }

This is how I call the function:

User clicks on add to cart:

<input type="button" value="<?php echo $lang['ADDTOCART']; ?>" class="addToCart" onclick="addtocart(<?php echo $itemId; ?>)" />

Javascript executed:

<script language="javascript">
    function addtocart(pid){
        document.cartAdding.itemId.value=pid;
        document.cartAdding.command.value='add';
        document.cartAdding.submit();
    }
</script>

Page reloads and comes into here:

if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' && $_REQUEST['itemId']>0)
{
        $pid=$_REQUEST['itemId'];
        addtocart($pid,1);
}

Thanks

samyb8
  • 2,560
  • 10
  • 40
  • 68

1 Answers1

2

You could put an if statement to check if the element has already been added. On top of my head, something like:

if (array_key_exists($pid, $_SESSION['cart']['itemId'])){ // check to see if product has already been added
 // put code statments here
}
C.O.D.E
  • 885
  • 8
  • 19
  • What if the user wants to add the same item again? It wouldn't add? – samyb8 Feb 14 '13 at 21:11
  • If the user wants to add the same item, then he wants to add another quantity (or substract the quantity); thus you would manage that inside the if statement. – C.O.D.E Feb 15 '13 at 14:34