0

I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;

.

The background

I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second). The button will just point back to this same page using the POST method.

The div on the right of the page will then load a "basket" which will use these post values and add them to an array.

When the "add" button is used again the value should update to +1 rather than create another sub_array.

.

What is currently happening

Currently when I click "add" the first time it adds the array as expected;

Result 1

However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.

Result 2

On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity

Result 3

It just seems to be that second time I click "add".

.

The Script

<?php session_start();

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

if (ISSET($_POST["prod"]))
{
    if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
    {
      $_SESSION["cart"][0] = 
      array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
    }
    else{
         echo 'running else';
         $_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}

         if ($_POST['e']=='1')
         {
           $_SESSION['cart'] = '';
         }
        echo '<br /><br />';
print_r($_SESSION["cart"]);
}

Sample form

<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
        <input type="hidden" value="1" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>

Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!

Many thanks to all in advance!

1
  • This is difficult to understand without a sample form. Commented Nov 28, 2018 at 13:15

2 Answers 2

1

I tried to debug your code and a possible solution could be the following:

<?php

 session_start();

if(!isset($_SESSION["cart"]))
{
    $_SESSION["cart"]=[];
}

if (isset($_POST["prod"]))
{
    $prod_id=$_POST["prod"];
    //let suppose $_POST['prod'] is your item id
    $found=false;
    for($i=0;$i<count($_SESSION['cart']);$i++)
    {
        if(isset($_SESSION['cart'][$prod_id]))
        {
            echo "found! so add +1";
            $_SESSION['cart'][$prod_id][2]+=1;
            $found=true;
            break;
        }
    }
    if($found==false)
    {
        echo 'not found! so create a new item';
        $_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
    }
}

         if (isset($_POST['e']) && $_POST['e']=='1')
         {
             $_SESSION['cart'] = '';
         }

        echo '<br /><br />';
print_r($_SESSION["cart"]);

?>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="1" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="2" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>

Another way to do it is using associative arrays. The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and an array with properties as name=>value for each item.

session_start();

if(!isset($_SESSION["cart"]))
{
    $_SESSION["cart"]=[];
}
//let's suppose you have unique names for items
if (isset($_POST["prod"]))
{
    $name=$_POST["name"];
    if(isset($_SESSION['cart'][$name]))
    {
        echo "found! so add +1";
        $_SESSION['cart'][$name]['quantity']+=1;
    }
    else
    {
       echo 'not found! so create a new item';
       $_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
    }
}

         if (isset($_POST['e']) && $_POST['e']=='1')
         {
             $_SESSION['cart'] =[];
         }

        echo '<br /><br />';
print_r($_SESSION["cart"]);

?>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="1" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="2" name="prod" />
    <input type="hidden" value="MAST-OMIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
</form>
Sign up to request clarification or add additional context in comments.

Comments

0

It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:

$_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);

For:

$_SESSION["cart"][0][2]+= 1;

By the way, try to properly indent your code when you are going to post it. It is hard to read.

2 Comments

Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go
This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.