简体   繁体   中英

First Item not being added to the session

I have a pretty basic shopping cart. The problem is that except for the first item in the list all other items are working fine. The way it works:

The products list coming from db have a button on each which is attached to a JS function which then, using the "load" jquery function it connects to a php script that adds the product to the session['basket']. I put an alert in the JS function and the first item (the one with the problem) looks fine. Also, put an echo " session exists" if a session is created in the php page. The first Icon does create a session, but shows no data like product name, etc.

Any help will be greatly appreciated.

Products List:

<?php require_once('inc.php');

  if ($prod->data != "") {
    foreach ($prod->data as $p) {

         if ($p['qty'] > 0) { ?>
            <ul style="text-align: left">
                <li><strong>Nome: </strong><?php echo $p['name']; ?> </li>
                <li><strong>Categoria: </strong><?php echo($p['category']); ?>      </li>
                <li><strong>Preço: </strong>&pound;<?php printf("%.2f", $p['priceUnit']); ?> </li>
                <li><strong>Stock: </strong><?php echo($p['qty']); ?> </li>
                <select id="<?php echo "prod_" . $p['id'] . "qty"; ?>" name="prodqty">
                    <?php
                    for ($i = 1; $i <= $p['qty']; $i++) {
                        echo '<option value="' . $i . '">' . $i . '</option>';
                    }
                    ?>
                </select> <br /><br />
            </li>
            <li><button class="button" onclick="addItem('<?php echo $p['id']; ?>', '<?php echo $p['name']; ?>', '<?php echo $p['category']; ?>',
                            '<?php echo $p['priceUnit']; ?>', '<?php echo "#prod_" . $p['id'] . "qty"; ?>');">Adicionar</button>
            </li>
            </ul>
        <?php
        }
    }
}

OUTPUT

     <div id="items">

        <?php if(isset($_SESSION['basket'])) {
                  echo "SESSION EXISTS";
                 $total = "";
                  foreach ($_SESSION['basket'] as $item){ ?>
                      <table>
                          <tr>
                              <td><?php echo $item['name'];?></td>
                              <td>&pound;<?php echo $item['price'];?></td>
                              <td> <?php echo $item['qty'];?></td>
                              <td><a href="<?php echo $_SERVER['PHP_SELF'];?>?id=<?php echo $item['id'];?>&amp; action=remove">Eliminar</a></td>
                          <tr>
                      </table>

                         <?php $total+= $item['subtotal'];?>

                      <?php  } ?>
                    <h3> Total a pagar: <span style="color:#000000">&pound;<?php printf("%.2f", $total);?></span></h3>

             <?php    }

                 ?>

        </div>
        <p class="output"></p>

JS:

 function addItem(id,name,cat,price,qty){

    alert('id: '+id+' name: '+name+' cat: '+cat+ ' price: '+price+' qty: '+$(qty).val());
    var qty2 = $(qty).val();
    var subtotal = price * qty2;
    if($('.output').load('basket.php',{name:name,price:price,cat:cat,id:id,qty2:qty2})){

       window.location.reload();
   }
}

PHP SCRIPT basket.php

  <?php require_once("inc.php");?>
 <?php


  $_id = CleanData($_POST['id']);
  $_name = CleanData($_POST['name']);
  $_price = CleanData($_POST['price']);
  $_qty = CleanData($_POST['qty2']);
  $_cat = CleanData($_POST['cat']);

  $basket = new ShoppingBasket();
  $basket->Add($_id,$_name, $_cat,$_price, $_qty);

?>

SHOPPING BASKET CLASS

<?php

class ShoppingBasket{


public function Add($id,$name,$cat,$price,$qty)
{

    //1. Check if the session basket exists
    if(!$_SESSION['basket']){


        $item=array('id'=>$id,
                    'name'=>$name,
                    'cat'=>$cat,
                    'price'=>$price,
                    'qty'=>$qty,
                    'subtotal'=>$qty * $price);           


        //store the first item in the session

        $_SESSION['basket'][$id]=$item;


     //2. Check if the item exists in the basket session

     }  else if ($_SESSION['basket'][$id]) {

         //update this item qty and subtotal

         $_SESSION['basket'][$id]['qty']+=$qty;
         $_SESSION['basket'][$id]['subtotal'] = $_SESSION['basket'][$id]['qty'] * $_SESSION['basket'][$id]['price'];


      //3. Add new Item to existing basket
       }else{
            //group parameters to associative array

        $item=array('id'=>$id,
                    'name'=>$name,
                    'cat'=>$cat,
                    'price'=>$price,
                    'qty'=>$qty,
                    'subtotal'=>$qty * $price);



        //Add new item to existing  basket

        $_SESSION['basket'][$id]=$item;

       }

    }
  }
?>

Try to combine the 1st and 3rd case of your conditions in the add method:

public function Add($id, $name, $cat, $price, $qty) {
    //1. Check if the session basket exists or the item exists in basket
    if (!$_SESSION['basket'] || !array_key_exist($id, $_SESSION["basket"])) {
        $item = array('id' => $id,
            'name' => $name,
            'cat' => $cat,
            'price' => $price,
            'qty' => $qty,
            'subtotal' => $qty * $price);
        //store the item in the session
        $_SESSION['basket'][$id] = $item;
    } else {
        //update this item qty and subtotal
        $_SESSION['basket'][$id]['qty']+=$qty;
        $_SESSION['basket'][$id]['subtotal'] = $_SESSION['basket'][$id]['qty'] * $_SESSION['basket'][$id]['price'];

    }
}

The other thing. This is really bad:

if(isset($_SESSION['basket'])) echo "SESSION EXISTS"; {

This means, if $_SESSION["basket"] exist, then echo something, and this is the end of your condition. (Anyway, the existing code will produce a syntax error.)

You should add the bracket right after the if:

if(isset($_SESSION['basket']))  {
    echo "SESSION EXISTS";
    //.....
}

I think it's because you are indexing the basket array with the product id coming from the db.

$_SESSION['basket'][$id]=$item;

This would not work if you do some operation that just loops through the array, like you do:

foreach ($_SESSION['basket'] as $item){ 
    //do something
}

because you don't have a product with 0 as id. Loops start from zero, maybe that's the issue. I think maybe you can do something like this, but this is not optimized code, I just would rethink the solution ASAP.

foreach ($_SESSION['basket'] as $item){ 
    if($item != array()){
        //do something if the item is not an empty array
    }
}

Hope this helps

Removed all the javascript and just used plain php. There must be a problem with the jQuery load() function and G Chrome I had something similar in another project where session would get updated but not always. It worked fine i FF though.

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