NTM NTM - 1 month ago 21
PHP Question

Sessions in shopping cart

I'm trying to show in a table the values that are stored in a session, the problem is: How to show all the information until now the application shows one of my three sessions, what about the rest? Any Idea?

<?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>

Answer

Maybe you need to change to:

<?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>

If you need to support multiple products in your app:

<?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>