0

i have a basket on my website where a user can add an item into the basket, remove it and increase the quantity. The item is posted to basket.php through a form. The form posts the id,quantity etc of the item to basket.php where the item is displayed. The quantity is displayed using input type = 'number' value = 'the quantity' correctly. Updating the quantity in basket.php which also updates the quantity in the database works aswell. My problem is: this only works for one item. if i add another item in the basket, the quantity for the last item in the basket is used for all other items in the basket, same thing happens when i update the quantity same quantity is used for all. How can i handle each item in the basket seperately so they are not treated as one.

My Code:

function.php

   <?php

  /****Function to display list of foods in the order page, 
  info button and the add to basket button********/

  function getFoo(){

   $conn = mysql_connect('localhost','root','') or trigger_error("SQL", 
   E_USER_ERROR);
   $db = mysql_select_db('1000_AD',$conn) or
   trigger_error("SQL", E_USER_ERROR); 

  $sql = "SELECT * FROM food LIMIT $offset, $rowsperpage";
  $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

  // while there are rows to be fetched...
  while ($list = mysql_fetch_assoc($result)) {


   $foo_id = $list['food_id'];
    $foo_cat = $list['food_cat'];
   $foo_type = $list['food_type'];
   $foo_title = $list['food_title'];
   $foo_price = $list['food_price'];
   $foo_image = $list['food_image'];

  // form below
  echo "<div class = 'single_food'>

  <form method='post' action='order.php'>

  <h4>$foo_title</h4>

  <div class = 'pic' ><img src='admin/food_images/$foo_image' width='180'  
  height= '160' /></div>

  <p><b>£$foo_price</b></p>

  <p><b>Qty</b> <input type='number' size='2' name='qty' style='width:30px'  
  min='1'  max = '99' value='1' /></p>

  <div class = 'btn'><a href='info.php?foo_id=$foo_id'  
  style='float:left'>INFO</a></div>

  <div id ='btn2'><input type='submit' name='add_basket'  id='submit'
  value='Add to Basket' /></div> 

         <input type='hidden' name='foo_id' value='$foo_id' />
        <input type='hidden' name='type' value='add' />
  <input type='hidden' name='return_url' value='$current_url' />
      </form>
  </div>";
  ?>

Order.php

 <?php 
  session_start();
  include ("functions/functions.php");
  ?>

 <?php
    //if add basket button is clicked post the food_id and quantity selected 
     to basket in database.

    if (isset($_POST['add_basket'])){

          global $con;

          $ip = getIp();

          $id = $_POST['foo_id'];
          $qty = $_POST['qty'];


             $check_foo = "select * from basket where ip_add= '$ip' AND f_id 

      = '$id'";
      $run_check = mysqli_query($con, $check_foo);

     if(mysqli_num_rows($run_check)>0){

     echo " ";
     }

    else {

     $insert_foo = "insert into basket (f_id,ip_add,qty) values ('$id',  
    '$ip',  '$qty')";
    $run_foo = mysqli_query($con, $insert_foo);

    $_SESSION['qty'] = $qty;

   echo "<script>window.open('order.php','_self')</script>";
     }

        }

      ?>

Basket.php

      <html>
      <head>
      <?php
       session_start();
       include ("functions/functions.php");
       </head>
      <body>
     <?php 
    //displays items in the basket and calculates sub total

      $total = 0;

      global $con;

      $ip = getIp();

      $sel_price = "select * from basket where ip_add='$ip'";

      $run_price = mysqli_query($con, $sel_price);

      while ($p_price = mysqli_fetch_array($run_price)) {

     $foo_id = $p_price['f_id'];

    $foo_price = "select * from food where food_id ='$foo_id'";

    $run_foo_price = mysqli_query($con, $foo_price);

    while ($ff_price = mysqli_fetch_array($run_foo_price)) {

    $food_price = array ($ff_price['food_price']);

    $food_title = $ff_price['food_title'];

    $food_image = $ff_price ['food_image'];

    $single_price = $ff_price['food_price'];

    $values = array_sum($food_price);

    $total += $values;
    ?>


     <?php 

     if (isset($_POST['update_quantity'])){

     $qty = $_POST['qty'];


    $update_qty = "update basket set qty='$qty' where f_id = '$foo_id' 
    and ip_add = ' $ip'";
    $run_qty = mysqli_query($con, $update_qty);

    $_SESSION['qty'] = $qty;

    $total = $values*$qty;

     }
      ?>
      <tr align="center">
     <td><input type="checkbox" name="remove[]" value="<?php echo $foo_id;?>" 
      /></td>
      <td><?php echo $food_title; ?><br>
      <img src="admin/food_images/<?php echo $food_image;?>"width="60" 
     height="60"/>
     </td>
       <td><input type="number" size="2" name="qty" style="width:30px"  
       min="1" max = "99" value ="<?php echo $_SESSION['qty'] ?>" /></td> 
      <td><?php echo "£".$single_price;?></td>

      </tr>

       <?php } } ?>
       <tr align="right">
      <td></td>
       <td></td>
       <td><b>Sub Total:</b></td>

       <td><?php 

       $_SESSION['total'] = $total;



       echo "£". number_format((float)$_SESSION['total'], 2, '.', ''); ?></td>
      </tr>
       <div id="up">
       <td><input type="submit" name="update_basket" value="Remove"></td>
       </div>
       <div id="up">
       <td>

      <input name="adjustBtn' . $foo_id . '" type="submit" 
     value="Update Quantity"/>
    <input name="update_quantity" type="hidden" value="<?php echo 
    $_SESSION['qty']  ?>" />
    </td>
    </div>
     <div id="con">
     <td><input type="submit" name="continue" value="Continue Shopping"></td>
     </div>
    <div id="chck">
     <td><a href="checkout.php"><button  type="hidden"           
       name="check">Checkout</button></a></td>
     <td>
    </div>

    </table>
    </form>
    </body>
    </html>

Can you please show how to this with for each? is it possible with jquery?

1 Answers1

1

Your project will really benefit from using AJAX -- and it's a LOT easier than it sounds.

AJAX will let you store the basket as a DB row, and dynamically send data to the basket without changing your page. In the success part of the AJAX block, you can modify the page you are on -- thereby killing two birds with one stone: (1) updating the basket record in the table, and (2) changing what is visible on the screen.

Design-wise, one approach could be to make each basket a table row, and have a column (cell) for basket items that you store in JSON format (JSON = array stored as text). For ease, you could also store this same string in a hidden input field on the form -- see this jsFiddle example -- and with each addition/deletion, just AJAX the changed "array" (json string) to the DB.

js code:

$('input[type="checkbox"]').click(function(){
    qty = prompt('How many?');
    tmp = hidInput.val();
    basket = (tmp=='') ? {} : JSON.parse( tmp );
    item = $(this).closest('tr').attr('id');
    basket[item] = qty;
    hidInput.val( JSON.stringify(basket) );

    $.ajax({
        type: 'post',
        url: 'path_to_your/php_processor_file.php',
        data: myJson=tmp,
        success: function(recd){
            //here, you can update the screen, like this:
            $('#someDiv').html(recd);
        }
    });
});

php_processor_file.php:

<?php

    $json = $_POST['myJson'];
    $arr = json_decode($json, true); //use true to turn into assoc array

    //now, do what you want with that PHP array: $arr

Here are some good posts for getting the basics of AJAX:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • @gibberish, Thanks for the info. From what i understand, i'm storing the items and quantity in a json array. do i include the code from php_processor_file to basket.php and how do i echo the data in the array? –  Mar 10 '15 at 23:20
  • php_processor_file.php *(can be renamed, but must also change name in ajax code block that calls it)* is probably a replacement for basket.php. Using AJAX, you would probably want to redesign your page / overall architecture design -- because you can now modify the database, get info from the database, and update things on the page you are on, *without ever leaving or refreshing the page.* Super useful, and -- in most cases -- well worth the redesign efforts. – cssyphus Mar 10 '15 at 23:26
  • OK Thanks, my only problem now is I'm a noob at Ajax. haven't used it anywhere in my site. :( . I don't mind redesigning the whole page but since I'll be designing whole thing I'll need hand holding for adding and deleting items in the basket. you've giving many options here which all involve ajax which do you think is closest to help solve the problem –  Mar 10 '15 at 23:44
  • Have you looked at those first three examples, in the answer above? Please do that -- you'll see it's a ton easier than it sounds. – cssyphus Mar 10 '15 at 23:50
  • alright, using the methods in the examples to post with ajax would fix the problem? –  Mar 10 '15 at 23:53