繁体   English   中英

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

[英]Making the add to cart button work for a simple webshop

我正在尝试使其在特定产品页面上按下“添加”按钮时,该产品被添加到$ _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>

上面的代码可以正常工作,并且可以毫无问题地保存所需的信息,但是刷新页面时也会添加项目。 我如何做到只有在按下“添加”按钮时才将商品添加到购物车? 我已经阅读了许多“解决方案”,但是以某种方式我无法使它们正常工作。 如果需要任何其他信息,可以将其发布。 提前致谢!

一种方法是在设置$ _SESSION之后重定向。

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();
}

您甚至可以根据需要设置“标志”以指示该商品已添加到购物车,并显示一条消息:

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>';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM