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 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决