du9826 2019-01-11 16:39
浏览 33

更新会话数组然后恢复到原始状态,如何停止此操作?

I am trying two simple buttons which will alter a cart's quantity by +1 or -1 depending on which button is clicked.

I set these up using 2 forms with a hidden value using post.

I then used an "if" and "ifelse" statement to determine which one (if any) was clicked.

I have compared to a very similar script doing something very similar (which works) and I can't see what I have done wrong.

The buttons

<?php
echo ' <form action="' .$_SERVER['PHP_SELF']. '" method="post">
        <input type="hidden" name="bn" value="1" />';
echo '<input type="hidden" name="pr" value="' .$key. '" />';
echo '<button style="min-width:25px;height:25px;background-color:white;"><b>+</b></button>
    </form>';

echo ' <form action="' .$_SERVER['PHP_SELF']. '" method="post">
    <input type="hidden" name="bn" value="2" />';
echo '<input type="hidden" name="pr" value="' .$key. '" />';
echo '<button style="min-width:25px;height:25px;background-color:red;"><b>-</b></button>';
echo '</form>';
?>

And the script for dealing with the POST data;

<?php
if($_POST["bn"]=="1")
{
    $_SESSION["cart"][$_POST["pr"]]["quantity"] += 1;
}
elseif($_POST["bn"]=="2") {
    if($_SESSION["cart"][$_POST["pr"]]["quantity"] == 1) { 
        unset($_SESSION["cart"][$_POST["pr"]]);
    }else{
        $_SESSION["cart"][$_POST["pr"]]["quantity"] -= 1;
    }
}
?>

Now the script works fine in the way that it will reload the page and will amend the quantity as per the button I clicked. Using both the normal output and print_r() I can see the session array HAS updated. However, if I now click another button on the page (the same one or different) the script will apply the update back to the original array data and not the one it should have just updated. I.e. if I sit there clicking +1 all day I will still only ever end up with 2 (the original one plus button the added one)

Please can someone help me find where I'm going wrong? Many Thanks!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line