Passing arrays via sessions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dmorris
Forum Newbie
Posts: 8
Joined: Mon Sep 23, 2002 5:09 pm

Passing arrays via sessions

Post by dmorris »

Hi guys,

I have the following code, which I am really struggling to understand what I have done wrong.

Code: Select all

<?php
if(!session_start()){
	echo "Failed when starting session";
	exit;	
}

//retrieve product array from session
if ( isset($_SESSIONї'products']) ) { $products = $_SESSIONї'products']; }

//retrieve variables from the request
if (isset($_REQUESTї'pid'])) { $pid = $_REQUESTї'pid']; }

$productsї] = array ("pid" => $pid, "quant" => 1);
session_register('products');

foreach ($products as $prod){
	echo "Product # ".$prodї'pid']." : ".$prodї'quant']."<br />";
}

echo "<a href="./index.php">Back</A>"
?>
when I revist with a different pid all the previous array entries have been removed.
dmorris
Forum Newbie
Posts: 8
Joined: Mon Sep 23, 2002 5:09 pm

Post by dmorris »

Sorry to waste your time, after spending all day searching, as soon as I posted the message I found the answer.

For those interested you can't use session_register and $_SESSION together.

I have changed my code to the following - which seems to work, but may not be the best way to do it. - any comments?

Code: Select all

<?php
if(!session_start()){
	echo "Failed when starting session";
	exit;	
}

//retrieve variables from the request
if (isset($_REQUESTї'pid'])) { $pid = $_REQUESTї'pid']; }

$_SESSIONї'products']ї] = array ("pid" => $pid, "quant" => 1);

foreach ($_SESSIONї'products'] as $prod){
	echo "Product # ".$prodї'pid']." : ".$prodї'quant']."<br />";
}
?>
Post Reply