March 6, 2012

PHP shopping cart doesn't show numerous products

Question by Carla Dessi

i’ve made a php shopping cart, it shows all the products on the home screen, you can click on them and add them to your basket, then you are taken to the shopping cart screen. this only shows one product but with a quantity of how many different products you’ve added, even if they all have different titles. the total price and quantity work, its only the product name that doesn’t. This is my code..

<?php
session_start();
include "connect.php";
include "header.php";

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 Name</th><th>Quantity</th><th>Delete</th></tr>";
    foreach ($cart as $product=>$quantity){
        $q = "SELECT ID, Name FROM Products";
        $result = mysqli_query($_SESSION['conn'],$q);
        $row = mysqli_fetch_array($result);
        $product_id = $row[0];
        echo "<tr><td>$product</td><td>$quantity</td><td><a href="?action=delete&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>There is no product in your shopping cart.</p>";
}


}

function addproduct($product_id, $product_qty){

$q = "SELECT ID, Name FROM Products";
$result = mysqli_query($_SESSION['conn'],$q)
 or die("Error: ".mysqli_error($_SESSION['conn']));
$row = mysqli_fetch_array($result);
$product_name = $row[1]; //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 Name FROM Products";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['Name'];
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;
        if ($cart[$product_name] == 0){ //if the quantity is 0, delete the key
            unset($cart[$product_name]);
        }
    }
    else { //exception
        echo "<p>Error!</p>";
    }
    $_SESSION['cart'] = $cart; //write the updated 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>";
}
}


function subtotal($cart){ //calculate the total value of products in the shopping cart
$total = 0; //initialise total
if (!empty($cart)){
    foreach ($cart as $product => $quantity){
        $q = "SELECT ID, Price FROM Products";
        $result = mysqli_query($_SESSION['conn'],$q);
        $row = mysqli_fetch_array($result);
        $price = $row['Price'];
        $total += $price * $quantity;
    }
    echo "<p>Total: $total | <a href="?action=empty">Empty cart</a></p>";
} else {
    unset($_SESSION['cart']); //do not need to keep an empty cart, so delete it
    echo "<p>There is no product in your shopping cart.</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();
        echo "<p><a href="javascript:history.go(-1)">back</a></p>";
    } else {
        echo "<p>There is an error! Are you trying to attack this little poor shopping cart?</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";

?>

Answer by Starx

You have a typo in your query. May be you wanted to extract the product id of the product, but, in fact selecting everything in a table.

$q = "SELECT ID, Name FROM Products";

Update it, to read something like the example below and check if this fixes the problem

$q = "SELECT ID, Name FROM `Products` WHERE name='$product' ";

And later you are reading the result as

$row = mysqli_fetch_array($result);

I hope you know that, this way $row will only get the first row it gets from the table.

February 28, 2012

How do I add new items to a cart and iterate through them to display using php?

Question by sharataka

I am trying to pass data from a product page into a shopping cart page using an array. There are multiple attributes that the viewcart.php will receive from the previous page (price, link, title, and retailer). I’d like to save them all using an array. For each additional item a customer adds to the shopping cart, I’m trying to get a counter variable ($i) to increment an array $_SESSION[‘cart’][$i][‘attribute’]. How do I do this?

I’m not sure this is the right way to add new products to the cart. In the end, I’d like a way to be able to display all the products in the cart using a for loop. This is the start I have so far on the shopping cart script:

<?php

  // The shopping cart needs sessions, so start one
  session_start();

  @$link = $_GET['link'];
$price = $_GET['price'];
$title = $_GET['title'];
$retailer = $_GET['retailer'];


  if($link) {
    //new item selected
    if(!isset($_SESSION['cart'])) {
      $_SESSION['cart'] = array();
      $_SESSION['items'] = 0;
      $_SESSION['total_price'] ='0.00';
    }

    if(isset($_SESSION['cart'][$link])) {
      $_SESSION['cart'][$link]++;
    } else {
      $_SESSION['cart'][$link] = 1;
    }


  }

  if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
    echo " in your cart and we're working to display them";
  } 
  else {
    echo "<p>There are no items in your cart</p><hr/>";
  }

?>

This is the for loop that I’m thinking I could use. I’m looking for some way to display all the items in the array.

for ($x=0; $x<=$i; $i++)
  {
  echo "The price is " . $_SESSION['cart'][$x][price] . "  Retailer is " . $_SESSION['cart'][$x]    [retailer] . "<br>";
  }

Answer by Faraz

The easiest way to do this is by creating a temp_cart table in your database.. in which you should store the items that user adds to their cart.. Then on checkout page.. you can simply display them using select query. In that way.. it will be easier for you to allow the user to edit their cart on viewcart.php page.

Answer by Starx

I don’t like the way you are doing this. Session management is very simple for shopping carts. Keep your session as lite as possible. Storing price in the session is very bad way, as it can be easily manipulated.

Here is a simple example of what you can use.

if(isset($_SESSION['items'][$_GET['item_id']])) {
    $_SESSION['items'][$_GET['item_id']]++; //add one to the total count
} else {
    $_SESSION['items'][$_GET['item_id']] = 1; //If added for the first time
}

Now process it

foreach($_SESSION['items'] as $id => $count) {
     echo $id; // product id
     echo $count; // product count
}

P.S: Remember to sanitize the input. I have omitted that

...

Please fill the form - I will response as fast as I can!