I would put them into functions, since you are probably going to be using this code often.
<?php
session_start();
function addProductToSession( $id,$code,$name ) {
$recView =& $_SESSION['recently_viewed'];
if ( count( $recView ) == 5 ) {
array_shift( $recView );
}
$recView[] = array( $id,$code,$name );
}
function getRecentlyViewedProducts() {
$ul = "<ul>\n";
foreach( $_SESSION['recently_viewed'] as $data ) {
list( $id,$code,$name ) = array_values( $data );
$ul .= "\t<li><a href=\"?PrdID={$id}\">{$code}</a> : {$name}</li>\n";
}
$ul .= "</ul>";
return $ul;
}
?>
kkeith29
Nearly a Posting Virtuoso
1,357 posts since Jun 2007
Reputation Points: 235
Solved Threads: 194
It sounds like you are running the getRecentlyViewedProducts() before adding a product. To fix the error use type-casting.
make foreach( $_SESSION['recently_viewed'] as $data ) into foreach( (array) $_SESSION['recently_viewed'] as $data ) . Or you can put
if ( !isset( $_SESSION['recently_viewed'] ) ) {
$_SESSION['recently_viewed'] = array();
}
at the top of the getRecentlyViewedProducts function.
As for their uses, put the add function right after you pull the product information from the database. Should be something like this:
addProductToSession( $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name'] );
then put echo getRecentlyViewedProducts() where you want the list to be displayed
kkeith29
Nearly a Posting Virtuoso
1,357 posts since Jun 2007
Reputation Points: 235
Solved Threads: 194
This is how the page should be layed out:
<?php
session_start();
function addProductToSession( $id,$code,$name ) {
$recView =& $_SESSION['recently_viewed'];
if ( count( $recView ) == 5 ) {
array_shift( $recView );
}
$recView[] = array( $id,$code,$name );
}
function getRecentlyViewedProducts() {
$ul = "<ul>\n";
foreach( $_SESSION['recently_viewed'] as $data ) {
list( $id,$code,$name ) = array_values( $data );
$ul .= "\t<li><a href=\"?PrdID={$id}\">{$code}</a> : {$name}</li>\n";
}
$ul .= "</ul>";
echo $ul;
}
//Query database for product info
//The $row_rsPrd is from the database result
addProductToSession( $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name'] );
getRecentlyViewedProducts();
?>
kkeith29
Nearly a Posting Virtuoso
1,357 posts since Jun 2007
Reputation Points: 235
Solved Threads: 194