Brent Hobson Brent Hobson - 3 months ago 21
PHP Question

php accessing sessions array

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,

Answer

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)."')";