Jump to content

Recommended Posts

Hey again,

Still on the same project but now doing the cart page.  I've been bringing my skills up to date a lot doing this project, however, having said that I now can't figure out why my cart is not adding the items to the cart, i've checked the post data and the quantity is set to 1.  Would really appreciate someone having a look at it and hopefully can see what i'm missing.

you can see what it should look like (well so far lol) at here in my sandbox site.

thanks again.

(p.s. The parts are all over the place on the page, so thought better put whole page, sorry if shouldn't have done that)

<?php
// Initialize the session
session_start();

// Include config file

require_once "dbcontroller.php";

$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
	case "add":
		if(!empty($_POST["quantity"])) {
			$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_code='" . $_GET["product_code"] . "'");
			$itemArray = array($productByCode[0]["product_code"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_code'=>$productByCode[0]["product_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["img1"]));

			if(!empty($_SESSION["cart_item"])) {
				if(in_array($productByCode[0]["product_code"],array_keys($_SESSION["cart_item"]))) {
					foreach($_SESSION["cart_item"] as $k => $v) {
							if($productByCode[0]["product_code"] == $k) {
								if(empty($_SESSION["cart_item"][$k]["quantity"])) {
									$_SESSION["cart_item"][$k]["quantity"] = 0;
								}
								$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
							}
					}
				} else {
					$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
				}
			} else {
				$_SESSION["cart_item"] = $itemArray;
			}
		}
	break;
	case "remove":
		if(!empty($_SESSION["cart_item"])) {
			foreach($_SESSION["cart_item"] as $k => $v) {
					if($_GET["product_code"] == $k)
						unset($_SESSION["cart_item"][$k]);
					if(empty($_SESSION["cart_item"]))
						unset($_SESSION["cart_item"]);
			}
		}
	break;
	case "empty":
		unset($_SESSION["cart_item"]);
	break;
}
}

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>LeaversHoodies.ie</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap-4.4.1.css" rel="stylesheet">
    <link href="css/accordian.css" rel="stylesheet">

  </head>
  <body>
    <?php include 'header_student.php'; ?>
<br />

<?php
$school_page = "ravenswell";

$sql = "SELECT * FROM schools WHERE school_page = '$school_page'";
if($result = mysqli_query($conn, $sql))
while($row = mysqli_fetch_array($result))

{
?>
     <h3 class="text-center">Student Ordering Page For</h3>
     <h2 class="text-center" style="text-transform:uppercase;"><?php echo $row['school_name']; ?></h2>

    <hr style="width: 50%; text-align:center; border: 2px solid #00aeef; border-radius: 5px; margin: 0 auto;">
<br />
    <div class="container">
      <div class="row">
        <div class="col">
        <?php $path = "images/schools/";
        $file = $row["logo"];

        if(!empty($row['logo'])) {
            echo '<img src="'.$path.$file.'" style="width:95%; height:auto; margin-top:-130px;"><br /><br />';
            } else {
            echo '<img src="images/schools/140x140.gif" style="width:95%; height:auto; margin-top:-130px;"><br /><br />';
        } ?></div>
        <div class="col-6">
<h5>These are the garments your school has choosen :</h5><br />
        <?php $school_id = $row["school_id"];
}
var_dump($_SESSION);
var_dump($_POST);
$product_array = $db_handle->runQuery("SELECT * FROM choices INNER JOIN products USING (product_code) INNER JOIN colours USING (colour_id) WHERE school_id = '$school_id'");
	if (!empty($product_array)) {
		foreach($product_array as $key=>$value){

      ?>
          <div class="container">
          <div class="row">
          <div class="col-5" style="text-align:left;">
              <img src="images/products/<?php echo $product_array[$key]["img1"]; ?>" alt="<?php echo $product_array[$key]["product_code"]; ?>" style="position:relative; top:0; width:200px; display:block;">
          </div>
          <div class="col-7">
            <h5><?php echo $product_array[$key]["product_name"]; ?></h5><p> in <?php echo $product_array[$key]["colour_name"]; ?></p>
            <p style="font-size:12px;"><?php echo $product_array[$key]["description"]; ?></p>

            <?php $comment = $product_array[$key]["comment"];
            if (empty($comment)) {
             echo "";
            } else { ?>
            <p style="font-size:12px;"><b>A note from your teacher:</b> <br />
            <?php echo $product_array[$key]["comment"]; ?></p>
            <?php }; ?>
                <form action="student_order.php?schoolname=<?php echo $school_page; ?>?action=add&product_code=<?php echo $product_array[$key]["product_code"]; ?>" method="post">
                <?php $product = $product_array[$key]["product_code"];  ?>
                    Please select your size :
                    <select id="size" name="size">
                      <?php
                      $sql1 = "SELECT DISTINCT * FROM sizes WHERE product_code = '$product'";
                      if($result1 = mysqli_query($conn, $sql1))
                      while($row3 = mysqli_fetch_array($result1)){
                            echo "<option value='" . $row3['size'] . "'>" . $row3['size'] . "</option>";
                        } else { echo "nothing to see here"; }
                      ?>
                    </select>
<br /><br />
                   <div class="number">How many do you want:
<input type="number" style="font-size:12px;" id="quantity" name="quantity" value="1" min="1" max="5"><br />
Price : <?php echo "€".$product_array[$key]["price"]; ?>
</div>
<input type="hidden" id="product_code" value="<?php echo $product; ?>"><br />
<input type="submit" style="font-size:12px;" value="Add to Order" class="btnAddAction">
                </form>

          </div>
          </div>
<br /><hr style="width: 90%; text-align:center; border: 1px solid #00aeef; border-radius: 5px; margin: 0 auto;"><br />
          </div>

<?php

          }
        } else {
          echo "No Schools by that name registered.";
        }

        ?>





</div>

<div class="col-3">
    <div style="border: 1px solid #d3d3d3; padding: 10px; border-radius: 5px; margin-top:30px;">
      Your Order:


    </div>

</div>
      </div>



<div class="txt-heading">Shopping Cart</div>

<a id="btnEmpty" href="student_order.php?schoolname=<?php echo $school_page; ?>?action=empty">Empty Cart</a>
<?php
if(isset($_SESSION["cart_item"])){
    $total_quantity = 0;
    $total_price = 0;
?>
<table class="tbl-cart" cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th style="text-align:left;">Name</th>
<th style="text-align:left;">Code</th>
<th style="text-align:right;" width="5%">Quantity</th>
<th style="text-align:right;" width="10%">Unit Price</th>
<th style="text-align:right;" width="10%">Price</th>
<th style="text-align:center;" width="5%">Remove</th>
</tr>
<?php
    foreach ($_SESSION["cart_item"] as $item){
        $item_price = $item["quantity"]*$item["price"];
		?>
				<tr>
				<td><img src="images/products/<?php echo $item["img1"]; ?>" class="cart-item-image" /><?php echo $item["product_name"]; ?></td>
				<td><?php echo $item["product_code"]; ?></td>
				<td style="text-align:right;"><?php echo $item["quantity"]; ?></td>
				<td  style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td>
				<td  style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td>
				<td style="text-align:center;"><a href="student_order.php?schoolname=<?php echo $school_page; ?>?action=remove&product_code=<?php echo $item["product_code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td>
				</tr>
				<?php
				$total_quantity += $item["quantity"];
				$total_price += ($item["price"]*$item["quantity"]);
		}
		?>

<tr>
<td colspan="2" align="right">Total:</td>
<td align="right"><?php echo $total_quantity; ?></td>
<td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td>
<td></td>
</tr>
</tbody>
</table>
  <?php
} else {
?>
<div class="no-records">Your Cart is Empty</div>
<?php
}

?>
</div>
    </div>


    <br /><br />

    <?php include 'footer_student.php'; ?>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery-3.4.1.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap-4.4.1.js"></script>

  </body>
</html>

 

<form action="student_order.php?schoolname=<?php echo $school_page; ?>?action=add&product_code=<?php echo $product_array[$key]["product_code"]; ?>" method="post">

Take a very, very close look at that line.

i thought it might be the quotes around product_code not (i think the term is ) escaping properly.  tried it still no joy.

<form action="student_order.php?schoolname=<?php echo $school_page; ?>?action=add&product_code=<?php echo $product_array[$key]['product_code']; ?>" method="post">
The url passes the product code

http://localhost/leavers/student_order.php?schoolname=ravenswell?action=add&product_code=JH004

and the post data shows its passing the size and quantity

array(2) { ["size"]=> string(1) "L" ["quantity"]=> string(1) "1" }

The cart still shows as empty, I tried to pear my cart down and just put in basic information, without the need for the schoolname etc and it works great, so maybe the add cart function is not working because of the schoolpage, either that or i'm totally missing something.

i'm really sorry i don't get it, if you mean that one is called schoolname and the other school_page i'm aware, school_page is the shortened version of the schoolname which i use for passing variables etc rather than the long name.   i tried moving the schoolname=school_page to the end of the line and it sort of worked, added a quantity of one but no other information was passed.

and the array results now look like :

array(1) { ["cart_item"]=> array(1) { [""]=> array(5) { ["product_name"]=> NULL ["product_code"]=> NULL ["quantity"]=> int(7) ["price"]=> NULL ["image"]=> NULL } } } array(2) { ["size"]=> string(1) "S" ["quantity"]=> string(1) "1" }

ohhhhhhhh, that second one should be an ampersand?  &

 

Edit: Yep tried and it should have been an &, thank you guys, felt like a prat when i finally saw it.  whole thing works like a charm now :)

Edited by MsKazza
Implemented the change

Ok well it was great for all of five minutes till i realized it is only adding one item, when i try to add another it just replaces the first item, i'm guessing there should be a counter being incremented for each item a new array.

    

	case "add":
		if(!empty($_POST["quantity"])) {
			$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_code='" . $_GET["product_code"] . "'");
			$itemArray = array($productByCode[0]["product_code"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_code'=>$productByCode[0]["product_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["img1"]));

			if(!empty($_SESSION["cart_item"])) {
				if(in_array($productByCode[0]["product_code"],array_keys($_SESSION["cart_item"]))) {
					foreach($_SESSION["cart_item"] as $k => $v) {
							if($productByCode[0]["product_code"] == $k) {
								if(empty($_SESSION["cart_item"][$k]["quantity"])) {
									$_SESSION["cart_item"][$k]["quantity"] = 0;
								}
								$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
							}
					}
				} else {
					$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
				}
			} else {
				$_SESSION["cart_item"] = $itemArray;
			}
		}

for some reason that i can't figure out yet the array_merge is not merging the two arrays.  I think the fault lies in this line $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); 

but not 100% sure, should it be adding(appending) using a + symbol?

Edited by MsKazza

array_merge will renumber arrays if they have numeric keys. Are your product_codes numeric?

Honestly, all that code is far more complicated than it needs to be. You're checking if the product_code exists in the cart so you can update its quantity, and then you run a loop over everything in the cart? And when you want to add the (new) item to the cart, you use array_merge instead of just adding the item directly to the cart array?

Try spending some time thinking about what's happening in there and whether there's any way you can reduce the number of lines to, say, half of what's there now.

your code is apparently (there's too much code to sift though to really tell what it is doing in all cases) using the product_code as the cart's array index. this is the preferred method, since you can DIRECTLY test or reference the data in the cart via its index. to test if the item is already in the cart, all you need is an isset() test. to modify or delete existing data, just directly modify/unset it via the index. to insert a new item into the cart, just set/assign it using the new array index value.

if the submitted product_code isn't valid (doesn't match any product/school choices) either due to a programming mistake, a product/choice being deleted after someone views the choices (choices shouldn't actually be deleted, just updated to indicate they are no longer available), or a nefarious data submission, you should setup an error message and report this condition to the visitor, i.e the selected product was not added to the cart, not a valid choice.

you have a select/option menu for size choices that there's currently no processing code for. different sizes of something should be a unique and separate product_code. if you cannot change the design to do this, you will need to validate the submitted size choice, store it in the cart, display it when the cart is displayed, then finally store it when the cart is converted to an order. you will also need to qualify any cart add/remove operation with the submitted size selection. if there's 2 large size of some product_code and 1 small size of some product_code in the cart and someone adds one more small size of that product_code, the correct quantity needs to be modified. i would add a second array index to handle this and for anything that doesn't have a size choice, use some unique size value to indicate not to treat the entry as a size choice.

lastly, don't put external, unknown, dynamic values directly into sql query statements. use a prepared query instead.

Edited by mac_gyver
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.