Member Avatar for ticallian

I'm trying to create an array to display the last 5 products a customer has viewed.

The array is a 2 dimensional array like below...
$RView= array(
array( ID => "1001", RefCode => "Ref_01", Name => "Name_01" ),
...
array( ID => "1005", RefCode => "Ref_05", Name => "Name_05" )
);

The array values are retrieved from the products recordset and is designed to function as follows when a customer visits a product page.

1. Page will check if a Session Array exists.
2a. If yes, an array variable is created from existing Session.
2b. If no, a new array is created.
3. Array will add the new product details.
4. Array will count if there are more than 5 existing products in the array.
5a. If yes, it will remove the oldest.
5b. If no, moves to step 6.
6. A Session is created/updated from the revised Array.

My current effort is attached below...
Many thanks for any help.

<?php 
    session_start() 
    // Get or Create Array
    IF (isset($_SESSION['sessRView'])) {
    $RView = ($_SESSION['sessRView']); } 
    ELSE {
    $RView = array(array()); 
    }

    // Append currently viewed Product to Array
    array(array_unshift($RView, $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name']));

    // Check if more than 5 products exist in Array, if so delete.
    IF (sizeof($RView) > 5) {
    array(array_pop($RView)); }

    // Update Session for next page
    $_SESSION['sessRView'] = $RView;

    // Display Array
    for ($row = 0; $row < 5; $row++)
    {
    echo "<ul>";
        echo "<li><a href='?PrdID=".$RView[$row]["PrdID"]."'>".$RView[$row]["RefCode"]."</a> : ".$RView[$row]["Name"]."</li>";
    echo "</ul>";
    }
?>

Recommended Answers

All 6 Replies

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

?>
Member Avatar for ticallian

Thanks for the detailed reply.
I'm having a little trouble understanding how the function works.

1. How does the function get the $id,$code,$name variables?
Do i preset them like " $id = $row_rsPrd; "

2. Am i meant to use any of my original code?
i.e. If its the first product visited and the Session doesn't yet exist, is it created, and then added to on further pages?

3. How am i meant to call the function?
" echo getRecentlyViewedProducts(); "?

Currently i've set the $id,$code,$name like i've stated above, and then done "echo getRecentlyViewedProducts();" to display the function.

However, i'm just getting an error
"Invalid argument supplied for foreach() " against the " foreach( $_SESSION as $data ) " line.
I'm guessing because its empty on the first attempt?

Thanks for the help.

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

Member Avatar for ticallian

I've made the suggested changes, the initial error is fixed.

However, i still can't get it working...
The change below generates an error expecting ")" which i can't fathom why as there's only 1 open bracket on the line.

addProductToSession( $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name'] ) {

I got around this by doing "$id= $row_rsPrd" etc and creating a the line as...

function addProductToSession($id,$code,$name) {

However, i'm now not getting anything echoed other than "<ul></ul>" suggesting the array just isn't picking anything up.

Other than the session array, with the one recordset, i'm working on a blank page so there shouldn't be anything conflicting.
The code is place immediately after the recordset.

<?php
$id = $row_rsPrd['PrdDetID'];
$code = $row_rsPrd['Refcode'];
$name = $row_rsPrd['Name'];

function addProductToSession($id,$code,$name) {
	$recView =& $_SESSION['recently_viewed'];
	if ( count( $recView ) == 5 ) {
		array_shift( $recView );
	}
	$recView[] = array( $id,$code,$name );
}

if ( !isset( $_SESSION['recently_viewed'] ) ) {
  $_SESSION['recently_viewed'] = array();
}
function getRecentlyViewedProducts() {
	$ul = "<ul>\n";
	foreach( (array) $_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;
}
?>
<?php 
echo getRecentlyViewedProducts();
?>

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();

?>
Member Avatar for ticallian

Works perfectly!

Thank you so much for the detailed responses.
It's the first time i've tried Daniweb and i'm impressed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.