In my code for shopping cart, sessions are not formed dynamically. I want to create session in this page and use sessions on the other page for item cart details.

How do I solve this problem?

<form  method="post" action="men.php?action=add&id=<?php echo 
        $product['id']; ?>"> 
      <img src="<?php echo $product['image'];?>">
      <img class="hover-img" src="<?php echo $product['h_image'];?>" >
      <p><?php echo $product['price'];?></p>
      <h6><?php echo $product['name'];?></h6>
      <input type="hidden" name="id" value="<?php echo $product['id']; ?>" />                                
      <input type="hidden" name="hidden_name" value="<?php echo 
        $product['name']; ?>" />
      <input type="hidden" name="hidden_price" value="<?php echo 
        $product['price']; ?>" />
      <input type="hidden" name="hidden_image" value="<?php echo 
        $product['image']; ?>" />
       Quantity <input type="text" class="form-control" name="qty" value="1" /><br>
       <input type="submit" name="cart" value="Add to Cart" />                       
   </form>

<?php
session_start();
if(isset($_POST['cart']))
{
// not working
     if(isset($_SESSION['shopping_cart']))
    {
        $count= count($_SESSION['shopping_cart']);
        $product_ids= array_column($_SESSION['shopping_cart'],'id');
        if(!in_array(filter_input(INPUT_GET,'id'),  $product_ids))
        {
            $_SESSION['shopping_cart'][$count]=array
            (
            'id'=> filter_input(INPUT_GET,'id'),
            'name'=> filter_input(INPUT_POST,'hidden_name'),
            'price'=> filter_input(INPUT_POST,'hidden_price'),
            'quantity'=> filter_input(INPUT_POST,'qty'),
            'image'=> filter_input(INPUT_POST,'hidden_image')
            );          
        }
        else
        {
             for($i=0; $i<count($product_ids); $i++)
            {
                if($product_ids[$i]==filter_input(INPUT_GET,'id'))
                {
                    $_SESSION['shopping_cart'][$i]['quantity']+= 
                     filter_input(INPUT_POST,'quantity');
                }
            } 
        }
    }
    else
    {           
    } 
}   
?>

1 Answers

0
Community On

Sara. The session_start(); should be the first line in your document.

So, it should look like:

<?php session_start(); ?>

and then the rest of your work

NOTE : IF IT STILL NOT WORKING PLEASE PROVIDE THE ERROR.