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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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;
	}
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.