简体   繁体   中英

Using session as a temporary cart

im building a website where in it i need to have a temporary cart, client doesnt want database so i have to deal with it by sessions. so here comes my question:

I have already set up a form which sends post actions to another php file and gets redirected to another page after action, i want the form to get added to the session as a new array on every submit, so i can show all cart details at checkout, but even when i use array_push i cant get it to work, it overwrites the previous array:

<form class="form-grey" action="<?php bloginfo('template_directory'); ?>/add_cart.php" method="POST">
  <input type="hidden" name="bikeName" value="<?php the_title(); ?>">
  <div class="row">
    <div class="col-sm-3">
      <label>Rent From:</label>
        <input type="text" id="fromDate" name="fromDate" class="datepicker">
    </div>
 <div class="col-sm-3">
  <label>Rent To:</label>
    <input type="text" id="toDate" name="toDate" class="datepicker" disabled>
    <button type="submit" name="Submit" class="btn btn-yellow">Add to Cart<span>+</span></button>

I have shortened the html code.

this is my add_cart.php

<?php

    session_start();

    $_SESSION['cart'] = array();

    $posts = array(
            'fromDate' => $_POST['fromDate'],
            'toDate' => $_POST['toDate'],
            'bikeName' => $_POST['bikeName'],
            'cyclistName' => $_POST['cyclistName'],
            'height' => $_POST['height'],
            'pedals' => $_POST['pedals'],
            'helmets' => $_POST['helmets'],
            'total' => $_POST['total']
        );

    array_push($_SESSION['cart'], $posts);

    header("Location: http://localhost:5555/mbr/checkout");
    die();

?> 

errm, are you trying to add multiple products to a cart upon each form submission? Because your $_session['cart'] data is being reset each time the shown code runs with the line

   $_SESSION['cart'] = array();

is meaning the cart array is empty. Anything that was previously in it has been cleared.

Solution: delete this line.

You must first check that the session isn't already set, and only define $_SESSION['cart'] as an empty array if it isn't. else you would be continuously overwriting an empty array.

if(!isset($_SESSION['cart']){
    $_SESSION['cart'] = array();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM