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>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题