购物车中的会话

时间:2016-10-22 14:04:11

标签: php session

我试图在表格中显示存储在会话中的值,问题是:如何显示所有信息,直到现在应用程序显示我的三个会话之一,其余的怎么样?有什么想法吗?

<?php
    $_SESSION['id'][] = $_GET['id'];
    $_SESSION['name'][] = $_GET['name'];
    $_SESSION['price'][] = $_GET['price'];
?>

<h1>Shopping Cart</h1><br>
<table border=1>
    <th>ID</th>
    <th>Name</th>
    <th>Price</th>
    <tbody id="tb">
    <?php foreach($_SESSION['name'] as $key=> $n){ ?>
    <tr>
        <td><?php ?></td>   
        <td><?php echo $n; ?></td>  
        <td><?php ?></td>               
    </tr>
   <?php } ?>
</tbody>
</table>

2 个答案:

答案 0 :(得分:0)

当用户点击退出按钮然后您将释放SESSION值并向用户弹出警报以获取清除购物车项目

 session_destroy();
 OR
 // remove all session variables
session_unset(); 

答案 1 :(得分:0)

也许您需要更改为:

<?php
     $product = array(
         'id' => $_GET['id'],
         'name' => $_GET['name'],
         'price' =>  $_GET['price'],
     );
     $_SESSION['product'] = $product;
?>

<h1>Shopping Cart</h1><br>
<table border=1>
    <thead>
         <tr>
             <th>ID</th>
             <th>Name</th>
             <th>Price</th>
         </tr>
    </thead>
    <tbody id="tb">
        <?php if isset($_SESSION['product']): ?>
        <tr>
             <td><?php echo $_SESSION['product']['id']; ?></td>   
             <td><?php echo $_SESSION['product']['name']; ?></td>   
             <td><?php echo $_SESSION['product']['price']; ?></td>    
        </tr>
        <?php endif; ?>
    </tbody>
</table>

如果您需要在应用中支持多种产品:

<?php
    // you can check that the cart exists, if not, create it.
     if (!isset($_SESSION['cart']){
        $_SESSION['cart'] = array(
            'products' => array(),
        );
     }
     $product = array(
         'id' => $_GET['id'],
         'name' => $_GET['name'],
         'price' =>  $_GET['price'],
     );
    //add 1 product to your cart
     $_SESSION['cart']['products'][] = $product;
?>

<h1>Shopping Cart</h1><br>
<table border=1>
    <thead>
         <tr>
             <th>ID</th>
             <th>Name</th>
             <th>Price</th>
         </tr>
    </thead>
    <tbody id="tb">
        <?php if isset($_SESSION['cart']): ?>
          //$product is only 1 product in the cart
            <?php foreach ($_SESSION['cart']['products'] as $product): ?>
            <tr>
                <td><?php echo $product['id']; ?></td>   
                <td><?php echo $product['name']; ?></td>   
                <td><?php echo $product['price']; ?></td>    
            </tr>
        <?php else: ?>
            <tr>
                <td>No products</td>    
            </tr>
        <?php endif; ?>
        </tr>
    </tbody>
</table>