Jump to content

Trying to get something to add to a SESSION


Recommended Posts

I'm trying to make my own shopping cart for the first time and having a problem getting products to add to it. All I get is "No product in cart.".

Its nothing special now, I'm just trying to reach the first stepping stone of adding something successfully to the session.

 

index.html

<?php session_start(); ?>
<?php
$cart = $_SESSION['cart'];
if (!$cart) {
	echo "No product in cart.";
}
if ($cart) {
	foreach ($id) {
		echo $id;
	}
}
?>
<A href="index.html?action=add&id=1">Add to cart</A>

 

What have I done wrong and what am I suppose to do?

After cleansing your data (i.e. don't trust what is actually coming in from the URL, or anywhere for that matter), you would add it to your cart by doing something like this:

 

// Check if we selected an action
if ( isset ( $_GET [ 'action' ] ) && $_GET [ 'action' ] == 'add' )
{
    // Since this is likely an auto-incremented ID, it should be an INT
    $id = intval($_GET['id']);

    // Validate that the item comes from the db (i.e. select from the table you pulled it from)
    
    // Validation successful, add the id to the cart
    $_SESSION['cart'][] = $id;
}

 

~juddster

Thanks man, your little trick worked. "No product in cart." no longer shows, but neither does the id.

 

<?php

if (isset ($_GET['action']) && $_GET ['action'] == 'add' ) {
	$id = intval($_GET['id']);
	$_SESSION['cart'][] = $id;
}
$cart = $_SESSION['cart'];

if (!$cart) {

	echo "No product in cart.";

}

if ($cart) {

	foreach ($id as $id) {

		echo $id;
	}
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.