0

Im currently working on a small university project. To develop a basic e-commerce php site. We have been given code or provided code within seminars which we are then to customise/develop further to our needs.

I am trying to adapt the following code to add an additional piece of information. The cart.php code builds a shopping cart functionality, which displays the product name, quantity and then allows the user to increase/decrease the quantity.

I am attempting to add the users (selected) product size to the shopping cart. Which they can select on product.php. I have already created the database support for this within product.php I just need the users selected option to then appear over in the cart.php.

Im not entirely sure how to do this correctly. My first problem is how do I record the users selection within product.php into a variable which can be transferred over to cart.php.

The second problem is then how to modify the cart.php to do this also, you shall see in cart.php I have attempted to add the product size to the table.

I really would appreciate some guidance with this.

Product.php

<div align="center"><?php
    session_start();
    //Connect to Session
    include "conn.php";

    //Retrieve Header
    include "header.php";

    //Query

    //Get Product ID
    if (isset($_GET['id'])){
        $product_id = $_GET['id'];

    //Select Product Attributes Query where Product ID is the selected product ID
        $q="SELECT ProductName,img,ProductID,Description,p_spec1,p_spec2,p_spec3,p_spec4,p_spec5,Price,size_1,size_2,size_3,size_4,size_5 FROM Products 
            WHERE ProductID=$product_id";

    //Retrieve and excute query from database and save results into a variable  
        $result = mysqli_query($_SESSION['conn'],$q);

    //Display Product
        if ($row = mysqli_fetch_array($result)){ //Create Product Attribute Array   
            echo "<div>
            <p><b>Name:</b>" .$row[0]."</p>

            <p><img src=".$row[1]."></p>

            <p><b>Product Code:</b>" .$row[2]."</p>

            <p><b><u>Product Description:</b></u></p>
            <p>".$row[3]."</p>

            <p><b><u>Product Spec:</b></u>";

            //Count total product specifications and adjust bullet points 
             for($i=4;$i<9;$i++) {
             if($row[$i]!='')
             echo "<li>".$row[$i]."</li>";
             }
             echo"  
            <p><b>Price: </b>&#163;".$row[9]."</p>

            <p><b>Size:</b><select>";

            //Count total product sizes available and adjust drop-down menu
             for($i=10;$i<15;$i++) {
             if($row[$i]!='')
             echo "<option>".$row[$i]."</option>";
             }
             echo"</select>             
            </p>

            </p>
            </div>";
        }

    //Add Item to basket
        echo "<div><a href=\"cart.php?action=add&product=$product_id,$product_size\"><input type='submit' value='Add to Basket'</a></div>";
    }

    //Retrieve Footer
    include "footer.php";
?>
</div>

I have assumed in product.php that a variable $product_size will need to be actioned over to cart.php, however how do I collect the users selection into a variable?

Cart.php

<?php

//Start Session
session_start();
include "conn.php"; //Connect to database
include "header.php"; //Retrieve Header

//View the current shopping cart session
function viewcart(){
    if (isset($_SESSION['cart'])){ //if shopping cart is not empty
        $cart = $_SESSION['cart']; //store the cart array into a variable then display the content
        echo "<table border=\"1\"> <tr> <th>Product</th> <th>Size</th> <th>Quantity</th> <th>Action</th></tr>";
        foreach ($cart as $product=>$quantity){
            $q = "SELECT ProductID FROM Products WHERE ProductName = '$product' LIMIT 1";
            $result = mysqli_query($_SESSION['conn'],$q);
            $row = mysqli_fetch_array($result);
            $product_id = $row['ProductID'];
            echo "<tr><td>$product</td>
                <td>$product_size</td>
                <td>$quantity</td><td> 
                <a href=\"?action=delete&product=$product_id\">-</a> 
                <a href=\"?action=add&product=$product_id\">+</a> </td> </tr>";
            mysqli_free_result($result);
        }
        echo "</table>";
        subtotal($cart); //display the subtotal
    } else { //if shopping cart is empty
        echo "<p>Your Basket is empty.</p>";
    }

}
function subtotal($cart){ 
    $total = 0; //initialise total
    if (!empty($cart)){
        foreach ($cart as $product => $quantity){
            $q = "SELECT Price FROM Products WHERE ProductName ='$product' LIMIT 1";
            $result = mysqli_query($_SESSION['conn'],$q);
            $row = mysqli_fetch_array($result);
            $price = $row['Price'];
            $total += $price * $quantity;
        }
        echo "<p>Total: &#163;$total | 
            <a href=\"?action=empty\">Empty cart</a></p>";
    } else {
        unset($_SESSION['cart']); //destroy empty cart
        echo "<p>Your Basket is empty.</p>";
    }
}
function addproduct($product_id, $product_qty){

    $q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
    $result = mysqli_query($_SESSION['conn'],$q);
    $row = mysqli_fetch_array($result);
    $product_name = $row['ProductName'];    //get the product name from product id because it is better to display name than id in the cart
    if (isset($_SESSION['cart'])){  //if shopping cart is not empty
        $cart = $_SESSION['cart'];
        if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
            $cart[$product_name] += $product_qty;
        }
        else {  //otherwise, add new product-quantity pair to the array
            $cart[$product_name]=$product_qty;
        }
    $_SESSION['cart'] = $cart; //write the updated array back to session variable
    }
    else { //if shopping cart is empty
        $cart = array($product_name=>$product_qty); //add product and quantity to the shopping cart
        $_SESSION['cart'] = $cart; //write the updated array back
    }
    mysqli_free_result($result);
}
function deleteproduct($product_id, $product_qty){
    $q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
    $result = mysqli_query($_SESSION['conn'],$q);
    $row = mysqli_fetch_array($result);
    $product_name = $row['ProductName'];
    if (isset($_SESSION['cart'])){ //if shopping cart is not empty
        $cart = $_SESSION['cart'];
        if (array_key_exists($product_name, $cart)){ //if product exists,                           update quantity
            $cart[$product_name] -= $product_qty;
            if ($cart[$product_name] == 0){ //if the qty 0, delete key
                unset($cart[$product_name]);
            }
        }
        else { //exception
            echo "<p>Error!</p>";
        }
        $_SESSION['cart'] = $cart; //write array back to session variable
    } else {
        echo "<p>Error!</p>";
    }
    mysqli_free_result($result);
}
function emptycart(){

    if (isset($_SESSION['cart'])){ //if shopping cart                       is not empty
        unset($_SESSION['cart']);
    }
    else {
        echo "<p>Error!</p>";
    }
}


if (isset($_GET['action'])){
    if ($_GET['action']=='view'){
        viewcart();
    } elseif ($_GET['action']=='add'){
        if (isset($_GET['product'])){
            $product_id = $_GET['product'];
            $product_qty = 1; //default product value
            addproduct($product_id, $product_qty);
            viewcart();
        } else {
            echo "<p>There is an error?</p>";
        }
    }
elseif ($_GET['action'] == 'delete'){
        if (isset($_GET['product'])){
            $product_id = $_GET['product'];
            $product_qty = 1; //default product value
            deleteproduct($product_id, $product_qty);
            viewcart();
        }
        else {
            echo "<p>There is an error!</p>";
        }
    } elseif ($_GET['action']=='empty') {
        emptycart();
        viewcart();
    }
    else {
        echo "<p>There is an error! </p>";
    }
}
else {   echo "<p>There is an error!</p>"; }

include "footer.php"; //template design part
?>

P.S I am aware of SQL injection issues.

Thank You!

2 Answers 2

1

I built something similar to this some time ago and faced the same (rather common) problem.

The solution requires you to create a session variable to store the selected product id's. I think I stored one or more arrays into the session and used the information to populate the checkout page.

I also stored the session data in a table so the user could access it between sessions, but that was a more advanced feature.

Take Away: use a session variable to store an array of product id's

Sign up to request clarification or add additional context in comments.

Comments

0

There are some fundamental flaws here.

To start, create valid HTML. Make sure the form is wrapped in <form></form> tags. That form should have an action: <form action="cart.php" method="POST">

Your select for "size" needs to have a name: <select name="productSize">.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.