2017-01-30 10 views
2

私は、特定の製品ページで「追加」ボタンを押すと、製品が$ _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> 

コードの上記部分は、問題なく動作していると、それは何の問題もなく、必要な情報を保存しますが、ページが更新されたときの項目も追加されます。 「追加」ボタンを押したときにアイテムがカートに追加されるようにするにはどうすればよいですか?私は多くの "解決策"を読んだことがありますが、どういうわけかそれらを正しく動作させることができませんでした。追加情報が必要な場合は投稿できます。前もって感謝します!

答えて

0

1つの方法は、$ _SESSIONが設定された後にリダイレクトすることです。

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

はどうもありがとうございました:

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

は、あなたも、必要に応じて、カートに追加された項目を示し、メッセージを表示するには、「フラグ」を設定することができます!これは私が探していた解決策でした。 – Daan

関連する問題