2

Before i start to explain in details, let me show the screenshot of what I want the result to be.

enter image description here

What I want to achieve is quite simple, display all the items that are added to cart and calculate the total for each individual product. However, looks like my Multidimensional Arrays and array_key_exists didn't do it correctly and that's why didn't get the result i want.

As you can see from the screenshot, if the same product being added to cart, the quantity didn't plus 1 and it just display below the previous item.

products.php -> nothing special, just to display all the products in database

<?php 
require 'config.php';
$q = mysqli_query( $db->conn(), "SELECT * FROM product" );

if( mysqli_num_rows($q) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc($q)){
    //echo "id: " . $row["id"]. " <br>- Name: " . $row["product_name"]. " " . $row["product_price"]. "";
     echo '<p>ID->'.$row['id'].' | '.$row['product_name'].' | $'.$row['product_price'].'
     | <a href="cart.php?id='.$row['id'].'">Add to Cart</a></p>';
}
}
?>

cart.php

<?php
session_start();

if(isset($_GET['id'])){

require 'config.php';
$id=$_GET['id'];
$q = mysqli_query( $db->conn(), "SELECT * FROM product where id='$id'" );
$row = mysqli_fetch_assoc($q);
$product_name=$row['product_name'];
$product_price=$row['product_price'];
$quantity=1;
$total=$quantity*$product_price;

if(!isset($_SESSION['cart'])){
    $_SESSION['cart'][]=[]; //Create session 1st time
}   
if(isset($_SESSION['cart'])){

    if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];

    }else {
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
    }

    echo '<table border="1" cellpadding="10">'; 
    echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
    foreach ($_SESSION['cart'] as $key => $row) { // list out all the items in Multi array
        echo "<tr>";
        foreach ($row as $key2 => $val) {
        echo "<th>";
        echo $_SESSION['cart'][$key][$key2]." ";
        echo "</th>";
        }
    echo "</tr>";
    }
    echo '</table>';

}
}
?>

May i know which part of the coding went wrong?

1
  • Why u dont let the SQL engine doing that ? Like SELECT Name, AVG(Price), SUM(Quantity), (Price*Quantity) as Total FROM product GROUP BY Name Commented Aug 16, 2016 at 8:42

2 Answers 2

2

Revisiting the Code in your cart.php File would be of great Benefit here. Below is what you may want to consider:

<?php
    $product_name   = $row['product_name'];
    $product_price  = $row['product_price'];
    $quantity       = 1;
    $total          = $quantity*$product_price;

    if(!isset($_SESSION['cart'])){
        $_SESSION['cart']           = [];
    }

    if(isset($_SESSION['cart'])){
        // DOES THE PRODUCT ID EXIST IN THE $_SESSION['cart'] COLLECTION?
        // IF IT DOESN'T WE CREATE IT AND LET IT BE...
        if(!array_key_exists( $id, $_SESSION['cart'] )){
            $_SESSION['cart'][$id]  = [$id, $product_name, $product_price, $quantity, $total];
        }else {
            // IF IT ALREADY EXIST; WE SIMPLY GET THE OLD VALUES & APPEND NEW ONE TO IT...

            // HERE YOU ASKED FOR array_key_exits($id, $_SESSION['cart']);
            // WHICH MEANS $id MUST BE THE KEY HERE
            // HERE IS WHERE THE PROBLEM IS....
            $storedPrice            = $_SESSION['cart'][$id][2];
            $storedQuantity         = $_SESSION['cart'][$id][3];
            $storedTotal            = $_SESSION['cart'][$id][4];
            $_SESSION['cart'][$id]  = [
                                        $id,
                                        $product_name,
                                        $product_price,
                                        $storedQuantity+1,
                                        round( ($storedQuantity+1)*($product_price), 2),
                                    ];
        }

        echo '<table border="1" cellpadding="10">';
        echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';


        foreach ($_SESSION['cart'] as $key => $row) {
            echo        "<tr>";
            foreach ($row as $key2 => $val) {
                echo    "<th>";
                echo    $_SESSION['cart'][$key][$key2]." ";
                echo    "</th>";
            }
            echo        "</tr>";
        }
        echo '</table>';

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

Comments

2

You have made the mistake, when add a Cart and Update Cart:

So change the following line:

if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
} 

Into

$find = false;
if(!empty($_SESSION['cart'])){
    foreach($_SESSION['cart'] as $key=>$cart){
        if(isset($cart[0]) && $cart[0] == $id){ //Already exists in Cart
            $_SESSION['cart'][$key][3] = $_SESSION['cart'][$key][3] + 1; //$_SESSION['cart'][$key][3] is quantity 
            $_SESSION['cart'][$key][4] = $_SESSION['cart'][$key][3] * $_SESSION['cart'][$key][2] ; //$_SESSION['cart'][$key][4] update the total
            $find = true;
        }
    }
}
if(!$find){ //Not in the Cart
    $_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}

Note: Before check, clear the cookies

1 Comment

your coding is not working :( the quantity didn't add correctly and also same item will display below one another

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.