2015-06-16 35 views
-1

我在5頁的邊欄中有一個簡單的表單,其中有兩個字段的名稱和價格。當用戶提交表單時,我想在會話中保存它的值。當我在提交表單後在會話中存儲它的值時,它每次都會替換名稱。但是我想存儲像數組這樣的名字值。如果用戶提交名稱爲user1的表單,然後再次提交用戶名user2,那麼我想在會話變量中顯示這兩個名稱,並希望顯示錶單增量提交。像推車功能一樣。有沒有辦法用單一表單來存儲這些值。請幫幫我。在會話中保存變量值,就像購物車一樣

<form id="myform" action="post.php" method="POST"> 
<div class="row"> 
    <label for="name">Your name:</label><br /> 
    <input id="name" class="input" name="name" type="text" value="" size="30" /><br /> 
</div> 
<div class="row"> 
    <label for="price">Price:</label><br /> 
    <input id="price" class="input" name="price" type="text" value="" size="30" /><br /> 
</div> 

<input id="submit_button" type="submit" value="submit" /> 
</form>  

post.php 
session_start(); 

$_SESSION['cart_items'] = array(); 
$_SESSION['cart_items'] = $_POST['name']; 

foreach($_SESSION["cart_items"] as $cart_item) 
{ 
    echo $cart_item; 
} 

回答

0

嘗試值由

session_start(); 
foreach ($_SESSION["products"] as $cart_itm) //loop through session array 
     { 
      if($cart_item["code"] == $product_code){ //the item exist in array 

      $product[] = array('name'=>$cart_item["name"], 'code'=>$cart_item["code"], 'qty'=>$product_qty, 'price'=>$cart_item["price"]); 
      $found = true; 
     }else{ 
      //item doesn't exist in the list, just retrieve old info and prepare array for session var 
      $product[] = array('name'=>$cart_item["name"], 'price'=>$cart_item["price"]); 
     } 
    } 

通過

foreach ($_SESSION["cart"] as $cart_item) 
{ 
echo $cart_item["price"]; 
$subtotal = ($cart_item["price"]*$cart_item["qty"]); 
$total = ($total + $subtotal); 
} 
echo $total; 
+0

添加到會話中添加的結果但是,當我打印$ _SESSION [「購物車」]這表明在這個車只有單一的價值。 – user3714488

+0

在**'foreach' **函數中使用你的echo變量,然後只顯示會話中的所有數組值... – Bruce

+0

我已經發布了我的代碼上面。它不工作。 – user3714488