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

时间:2017-01-30 22:05:17

标签: php html

我试图这样做,以便当"添加"按钮在特定产品页面上按下,产品将添加到$ _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>

上面的代码工作没有任何问题,它可以毫无问题地保存所需的信息,但是在刷新页面时也会添加项目。我怎样才能使项目只在&#34;添加&#34;按下按钮?我已经阅读过许多解决方案&#34;但不知怎的,我无法让它们正常工作。如果需要任何其他信息,我可以发布。提前谢谢!

1 个答案:

答案 0 :(得分:0)

一种方法是在设置$ _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>';
}