3

i am still relatively new to php and this site, so i apologise now!This is driving me crazy, i'm trying to add an array to session state for a shopping cart i am piecing together from different bits of code....

    $_SESSION['cart_items'] = 
array(
       'product_name' => $name,
       'productId' => $id,
       'quantity' => 1
);

^that is the part where it adds to the session state, this works fine as i printr and it comes out like this

Array ( [product_name] => The Ned Rose [productId] => 1 [quantity] => 1 )

This is the bit that i cant get to work. How do i access the product ID's so i can use them in a SQL query to fetch the data to populate the cart...

if(count($_SESSION['cart_items'])>0){
$ids = "";
foreach($_SESSION['cart_items']['productId'] as $id=>$value){
    $ids = $ids . $id . ",";

}

Thanks,

EDIT HERE THE CART PAGE can anyone see where i am going wrong?

<?php
session_start();
$page_title="Cart";
include 'mysql.php';
print_r($_SESSION['cart_items']);
$action = isset($_GET['action']) ? $_GET['action'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='removed'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> was removed from your cart!";
echo "</div>";
}

else if($action=='quantity_updated'){
echo "<div class='alert alert-info'>";
    echo "<strong>{$name}</strong> quantity was updated!";
echo "</div>"; 
}
if(count($_SESSION['cart_items'])>0){
$ids = "";
$ids = array_keys($_SESSION['cart_items']);
foreach($_SESSION['cart_items'][$id] as $key=>$value){
    $ids = $ids . $id . ",";
}


// remove the last comma
$ids = rtrim($ids, ',');

//start table
echo "<table class='table table-hover table-responsive table-bordered'>";

    // our table heading
    echo "<tr>";
        echo "<th class='textAlignLeft'>Product Name</th>";
        echo "<th>Price (GBP)</th>";
        echo "<th>Action</th>";
    echo "</tr>";

    $query = "SELECT prodID, prodName, prodPrice FROM product_tbl WHERE prodID IN ({$ids}) ORDER BY prodName";
    $result = mysqli_query($db, $query);
    $total_price=0;
    while ($row = mysqli_fetch_assoc($result)){
        extract($row);

        echo "<tr>";
            echo "<td>".$row['prodName']."</td>";
            echo "<td>£".$row['prodPrice']."</td>";
            echo "<td>";
                echo "<a href='remove_from_cart.php?id=".$row['prodID']."&name=".$row['prodName']."' class='btn btn-danger'>";
                    echo "<span class='glyphicon glyphicon-remove'></span> Remove from cart";
                echo "</a>";
            echo "</td>";
        echo "</tr>";

        $total_price+=$row['prodPrice'];
    }

    echo "<tr>";
            echo "<td><b>Total</b></td>";
            echo "<td>£{$total_price}</td>";
            echo "<td>";
                echo "<a href='#' class='btn btn-success'>";
                    echo "<span class='glyphicon glyphicon-shopping-cart'></span> Checkout";
                echo "</a>";
            echo "</td>";
        echo "</tr>";

echo "</table>";

}

else{ echo ""; echo "No products found in your cart! Click Here To Return To The Store"; echo ""; }

?>

5
  • $_SESSION['cart_items']['productId'] will get your the cart ID Commented Aug 18, 2016 at 14:30
  • but I would like to also add you would probably be best adding the basket line to a DB table rather than a session Commented Aug 18, 2016 at 14:31
  • the content of $_SESSION['cart_items']['productId'] doesnt seem to be an array, why do you use a "foreach" on it ? As well, I think you should have a look at implode function (php.net/manual/fr/function.implode.php) Commented Aug 18, 2016 at 14:32
  • thanks all, Still no luck, still cant even print out the IDS......... Commented Aug 18, 2016 at 14:51
  • 1
    Your cart only holds one item, because $_SESSION['cart'] = ... will always overwrite whatever was in there previously. you need to have an ARRAY of cart items, e.g. $_SESSION['cart'][$productID] = array(...details...) Commented Aug 18, 2016 at 14:51

3 Answers 3

2

Use $id as the KEY value when storing the product in the cart:

$_SESSION['cart_items'][$id] = 
array(
       'product_name' => $name,
       'productId' => $id,
       'quantity' => 1
);

Then you can use the ID in the foreach loop:

if( count($_SESSION['cart_items']) > 0){
    foreach($_SESSION['cart_items']['productId'] as $id => $value){
       // Get data for this product

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

Comments

0

You could add products to the array so that you didn't need to directly store the "productId" value.

// Set data
$_SESSION['cart_items'][$id] = Array('name'=>$name,'qty'=>1);

// Show session content
foreach($_SESSION['cart_items'] as $id=>$props){
    echo 'id='.$id.'<br />';
    echo 'name='.$props['name'].'<br />';
    echo 'qty='.$props['qty'];
}

// Collect ids (result is an array of ids)
$ids = array_keys($_SESSION['cart_items'];

// Use $ids in a query
$sql = "SELECT * FROM your_table WHERE id_field IN('".implode("','",$ids)."')";

1 Comment

most of my successes are flukes, i used this answer and instead of echo'n the session out i put the ids += id . id line in and it worked!
0

You can use the followings

$_SESSION['cart_items'][] = 
array(
       'product_name' => $name,
       'productId' => $id,
       'quantity' => 1
);

or (this will update previously added product id in the cart)

$_SESSION['cart_items'][$id] = 
array(
       'product_name' => $name,
       'productId' => $id,
       'quantity' => 1
);


if(count($_SESSION['cart_items'])>0){
$ids = "";
foreach($_SESSION['cart_items'] as $id=>$value){
    $ids = $ids . $id . ",";

 }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.