dqwh1203 2017-01-30 22:05
浏览 301
已采纳

使添加到购物车按钮适用于简单的网上商店

I'm trying to make it so that when the "add" button is pressed on a specific product page the product is added to a $_SESSION.

if(isset($_POST['add'])) {
$_SESSION['cart'] [] = array('product_name' => $result['name'], 'product_price'=> $result['price'], 'product_id' => $result['id']); }

<form method="post">
<input type="submit" class="button blueboxbutton userAccountButton" name="add" value="add"></input></br>
</form>

The above piece of code is working without any problems and it saves the required information without any problems, but items are also added when the page is refreshed. How can I make it so that items are only added to the cart when the "add" button is pressed? I've read many "solutions", but somehow I couldn't get them to work correctly. If any additional information is needed I can post it. Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongyue3795 2017-01-30 22:11
    关注

    One method is to redirect after the $_SESSION has been set.

    if( isset( $_POST['add'] ) ) {
        $_SESSION['cart'][] = [ 'product_name'  => $result['name'],
                                'product_price' => $result['price'],
                                'product_id'    => $result['id']
                              ]; 
        // redirect to this same page, but without the $_POST variables
        header('location: ' . $_SERVER[ 'PHP_SELF' ] );
        // If you don't die() after redirect, sometimes doesn't actually redirect
        die();
    }
    

    You could even, if desired, set a "flag" to indicate the item was added to cart, and display a message:

    if( isset( $_POST['add'] ) ) {
        $_SESSION['cart'][] = [ 'product_name'  => $result['name'],
                                'product_price' => $result['price'],
                                'product_id'    => $result['id']
                              ]; 
         $message = urlencode( $result['name'] . ' added to cart.' );
         // redirect to this same page, but without the $_POST variables
         header( 'location: ' . $_SERVER[ 'PHP_SELF' ] . '?message=' . $message );
         // If you don't die() after redirect, sometimes doesn't actually redirect
         die();
    }
    
    // Elsewhere in your code display a message if set...
    if ( ! empty( $_GET[ 'message' ] ) ) {
        // urldecode is used because we urlencoded above
        // htmlspecialchars is used to help "sanitize" the display
        echo '<div class="message">' . htmlspecialchars( urldecode( $_GET['message'] ) ) . '</div>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常