close ad
 
Important WebAssist Announcement
open ad
View Menu

Web development tutorial

How to display a list of ‘recently viewed' products

Tutorial created by CraigR, ForthWebSolutions

Categories: Data Bridge, eCart, MySQLi Server Behaviors, MySQL, PHP

rating

On a number of ecommerce sites, a short browsing history is displayed, which allows the user to browse back more easily to a product they have just seen, or to act as a reminder so they don’t forget about something which may have interested them.

In this tutorial, I will use a potential customer’s browsing history to display the last 5 products viewed, by storing the productid from the product details page in an array.

arrow downObjectives

Here is a short list of what I want to achieve...

• Add the selected product id to an array when the product detail page is loaded
• Store up to 5 product ids in my array
• Prevent the same product being added to the array twice
• Use the array contents to filter a recordset, so I can display images of the products with a hyperlink to the product details page.

Step 1: Adding the product id to an array

At the top of the product detail page, create/set a session value.

You can do this with an ecart server behaviour, using Add->Ecart->General->Set Session Value



Here I used 'lastviewed' as the session name.
The resulting code block will need to be edited to remove the inverted commas around array().

The embedded code should look like this...

<?php
@session_start();
if(!isset($_SESSION["lastviewed"])) {
$_SESSION["lastviewed"] = array();
}
?>

Step 2: Using the URL Parameter

Now I want to use the URL Parameter, GET[‘ProductID’], which is being used to filter the products recordset on my productdetail page, and add it to my array.

Firstly, I am creating a php variable called $maxelements, and setting the value to 5.

(Set this to any integer, according to how many ids you wish to store in your array.)

I am then checking that my page has a url parameter and that if set, it is not an empty string

$maxelements = 5;
if (isset($_GET['ProductID']) && $_GET['ProductID'] <> "") {// if we have url parameter

...

}



I then check the number of elements in my array.
If there are 5 elements in my array already, I then use the php function array_slice() to remove the first array element

$maxelements = 5;
if (isset($_GET['ProductID']) && $_GET['ProductID'] <> "") {// if we have url parameter

if (count($_SESSION["lastviewed"]) >= $maxelements) {//check the number of array elements
$_SESSION["lastviewed"] = array_slice($_SESSION["lastviewed"],1); // remove the first element if we have 5 already


}



Then I use the php function array_push() to add the current itemid to the array

<?php
@session_start();
if(!isset($_SESSION["lastviewed"])) {
$_SESSION["lastviewed"] = array();
}

$maxelements = 5;
if (isset($_GET['ProductID']) && $_GET['ProductID'] <> "") {// if we have url parameter

if (count($_SESSION["lastviewed"]) >= $maxelements) {//check the number of array elements

$_SESSION["lastviewed"] = array_slice($_SESSION["lastviewed"],1); // remove the first element if we have 5 already

array_push($_SESSION["lastviewed"],$_GET['ProductID']);//add the current itemid to the array
} else {
array_push($_SESSION["lastviewed"],$_GET['ProductID']);//add the current itemid to the array

}

}

?>



The result of the above code will be an array with up to 5 values stored within it, each value being a ProductID retrieved from a product details page.

Step 3: Ensure there are no duplicates

To finish it off, I now want to ensure that the same product isn’t added to the array twice.

To do this, I check and see if the productid is in the array, BEFORE I push the array element onto the end of the array. and if it is already there, remove it.

This is done with the php function array_diff(), which compares 2 arrays and returns the difference between them.

This also means the most recent instance of the productid is stored in the array, so If the product was added 4 clicks ago, I won’t now lose it immediately when the array is next updated.

Here is my final code block

<?php
@session_start();
if(!isset($_SESSION["lastviewed"])) {
$_SESSION["lastviewed"] = array();
}
$maxelements = 5;
if (isset($_GET['ProductID']) && $_GET['ProductID'] <> "") {// if we have url parameter

if (in_array($_GET['ProductID'], $_SESSION["lastviewed"])) { // if product id is already in the array
$_SESSION["lastviewed"] = array_diff($_SESSION["lastviewed"],array($_GET['ProductID'])) ; // remove it
$_SESSION["lastviewed"] = array_values($_SESSION["lastviewed"]); //optionally, re-index the array
}


if (count($_SESSION["lastviewed"]) >= $maxelements) {//check the number of array elements
$_SESSION["lastviewed"] = array_slice($_SESSION["lastviewed"],1); // remove the first element if we have 5 already
array_push($_SESSION["lastviewed"],$_GET['ProductID']);//add the current itemid to the array
} else {
array_push($_SESSION["lastviewed"],$_GET['ProductID']);//add the current itemid to the array
}

}
?>

Step 4: Using the array values

That’s it for getting the data

In order to use these values, I need to manipulate the array so I can get a string of values to use as my filter criteria.

To do this, I need to use the implode() fuction, to convert my array into a comma separated string.

<?php
@session_start();
$criteria = (isset($_SESSION["lastviewed"])?implode(", ",$_SESSION["lastviewed"]):"-1");
?>

Step 5: Creating the SELECT query (MySQL)

For MySQLi, skip this step and move on to step 6

Here, the objective is to list the products which appear in the array, in the order that they were added, so that the products selected most recently will appear last.

In practice, I find more complex queries are harder to write using the add recordset binding method in Dreamweaver, so what I tend to do is write a simple query and hand code it afterwards.

Below I have attempted to write the select statement (almost) entirely within the dreamweaver binding method, and edited it as necessary

The basic structure is as follows. selecting the key fields I need from the Products table, to display a product and its image.



Notice that the Data type for the variable is set as integer.

This setting will not work when I run the quesry, so I need to change this in the code

From the code produced from the add recordset binding method in Dreamweaver, I changed the line

$query_rslastviewed = sprintf("SELECT ProductID, ProductName, ProductImageTitle, ProductImage FROM tblproducts WHERE ProductID IN (%s)", GetSQLValueString($varproductid_rslastviewed, "number"),GetSQLValueString($varproductid_rslastviewed, "int"));



to

$query_rslastviewed = sprintf("SELECT ProductID, ProductName, ProductImageTitle, ProductImage FROM tblproducts WHERE ProductID IN (%s)  ORDER BY FIELD (ProductID, %s)", GetSQLValueString($varproductid_rslastviewed, "number"),GetSQLValueString($varproductid_rslastviewed, "number"));



Changing the “int” value to “number” and adding the ORDER BY statement to the end of the string.

I don’t know if this is the best way to do this, but the criteria now works as expected giving me the result I expect, in the intended order.
Now it is simply a case of displaying the records

Step 6: Creating the SELECT query (MySQLi)

For MySQL, ignore this step and move back to step 5

Here, the objective is to list the products which appear in the array, in the order that they were added, so that the products selected most recently will appear last.


Select Server Behaviors -> + -> Webassist -> MySQLi -> MySQLi Recordset
(Make sure you are in advanced view)

The basic structure is as follows, selecting the key fields I need from the Products table, to display a product and its image.
I also need to filter the recordset using the values in my criteria variable and also order the recordset using the same criteria.
First, the filter parameter



Notice that the Data type for the variable is set as integer and the variable is a comma separated list
After the filter, I add the order by clause,



the final sql statement should look like this…

<?php 
$rslastviewed = new WA_MySQLi_RS("rslastviewed",$PowerCMSConnection_i,0);
$rslastviewed->setQuery("SELECT tblproducts.ProductID, tblproducts.ProductName, tblproducts.ProductImageTitle, tblproducts.ProductImage FROM tblproducts WHERE tblproducts.ProductID IN (?) ORDER BY FIELD (tblproducts.ProductID, ?)");
$rslastviewed->bindParam("il", "".$criteria ."", "-1"); //criteria
$rslastviewed->bindParam("il", "".$criteria ."", "-1"); //listorder
$rslastviewed->execute();
?>

Step 7: Displaying the records

As an example, insert an image tag and make it into a link
Create a repeat region for the link to display all of the rows in the recordset.

eg MySQL

<?php do { ?>
<a href="productdetails.php?ProductID=<?php echo $row_rslastviewed['ProductID']; ?>"><img src="<?php echo $row_rslastviewed['ProductImage']; ?>" title="<?php echo $row_rslastviewed['ProductID']; ?>" width="150" alt="Image of <?php echo $row_rslastviewed['ProductImage']; ?>"/></a>
<?php } while ($row_rslastviewed = mysql_fetch_assoc($rslastviewed)); ?>



eg MySQLi

<?php while(!$rslastviewed->atEnd()) { ?>
<a href="productdetails.php?ProductID=<?php echo $rslastviewed->getColumnVal("ProductID"); ?>"><img src="<?php echo $rslastviewed->getColumnVal("ProductImage"); ?>" title="<?php echo $rslastviewed->getColumnVal("ProductID"); ?>" width="150" alt="Image of <?php echo $rslastviewed->getColumnVal("ProductImage"); ?>"/></a>
<?php $rslastviewed->moveNext(); }
$rslastviewed->moveFirst(); //return RS to first record
?>




This is my first tutorial, I hope you found it useful and easy to follow.
If you have any questions, or can offer suggestions for improvements, please let me know,
(Modified September 2015 with updates for mySQLi)

arrow downReviews and comments

Comments will be sent to the author of this tutorial and may not be answered immediately. For general help from WebAssist, please visit technical support.

Sign in to add comments
rating
rating

Nico: 9 Years, 9 Months, 1 Week, 5 Days, 4 Hours, 24 Minutes ago

Great Tutorial! Well done. Implemented the same using mysqli behavior. It is even easier. In the last step you handcode mysql result. Using mysqli you just check the comma seperated value and change '=' to 'IN'.

Once again thank you for this super easy to follow tutorial

rating

Nico: 9 Years, 8 Months, 4 Weeks, 7 Hours, 46 Minutes ago

Just to make a correction, you dont really have to change '=' to 'IN'.

: 5 Years, 1 Week, 2 Days, 10 Hours, 35 Minutes ago

i am getting this error- [26-Nov-2019 14:07:56 UTC] PHP Parse error: syntax error, unexpected '$rslastviewed' (T_VARIABLE), expecting ',' or ';' in /home/fbt5bixmgpkq/public_html/dailyShop/product.php on line 301
This is my code:
<?php
//Add the selected product id to an array when the product detail page is loaded
session_start();
if(!isset($_SESSION["lastviewed"])) {
$_SESSION["lastviewed"] = array();
}
//Store up to 5 product ids in my array
$maxelements = 5;
if (isset($_GET['id']) && $_GET['id'] <> "") {// if we have url parameter
//Prevent the same product being added to the array twice
if (in_array($_GET['id'], $_SESSION["lastviewed"])) { // if product id is already in the array
$_SESSION["lastviewed"] = array_diff($_SESSION["lastviewed"],array($_GET['id'])) ; // remove it
$_SESSION["lastviewed"] = array_values($_SESSION["lastviewed"]); //optionally, re-index the array
}

if (count($_SESSION["lastviewed"]) >= $maxelements) {//check the number of array elements
$_SESSION["lastviewed"] = array_slice($_SESSION["lastviewed"],1); // remove the first element if we have 5 already
array_push($_SESSION["lastviewed"],$_GET['id']);//add the current itemid to the array
} else {
array_push($_SESSION["lastviewed"],$_GET['id']);//add the current itemid to the array
}

}
?>

<?php
//Use the array contents to filter a recordset, so I can display images of the products with a hyperlink to the product details page.
@session_start();
$criteria = (isset($_SESSION["lastviewed"])?implode(", ",$_SESSION["lastviewed"]):"-1");

$rslastviewed = new WA_MySQLi_RS("rslastviewed",$PowerCMSConnection_i,0);
$rslastviewed->setQuery("SELECT products.id, products.productName, products.productImage1 FROM products WHERE products.id IN (?) ORDER BY FIELD (products.id, ?)");
$rslastviewed->bindParam("il", "".$criteria ."", "-1"); //criteria
$rslastviewed->bindParam("il", "".$criteria ."", "-1"); //listorder
$rslastviewed->execute();
?>



<!-- single sidebar -->

<div class="aa-sidebar-widget">

<h3>Recently Views</h3>
<div class="aa-recently-views">
<?php while(!$rslastviewed->atEnd())
{
?>
<ul>
<li>
line no-301 :- <a href="product-details.php?id=<?php echo htmlentities $rslastviewed->getColumnVal("id"); ?>" class="aa-cartbox-img">
<img alt="img" src="admin/productimages/<?php echo htmlentities $rslastviewed->getColumnVal("productImage1"); ?>" title="<?php echo htmlentities $rslastviewed->getColumnVal("id"); ?>"
width="150" /></a>
<div class="aa-cartbox-info">
<h4><a href="#"><?php echo htmlentities $rslastviewed->getColumnVal("productName"); ?></a></h4>
<p><?php echo htmlentities $rslastviewed->getColumnVal("productPrice"); ?></p>
</div>
</li>

</ul>
<?php
$rslastviewed->moveNext();
}
$rslastviewed->moveFirst();
?>
</div>

</div>

Build websites with a little help from your friends

Your friends over here at WebAssist! These Dreamweaver extensions will assist you in building unlimited, custom websites.

Build websites from already-built web applications

These out-of-the-box solutions provide you proven, tested applications that can be up and running now.  Build a store, a gallery, or a web-based email solution.

Want your website pre-built and hosted?

Close Windowclose

Rate your experience or provide feedback on this page

Account or customer service questions?
Please user our contact form.

Need technical support?
Please visit support to ask a question

Content

rating

Layout

rating

Ease of use

rating

security code refresh image

We do not respond to comments submitted from this page directly, but we do read and analyze any feedback and will use it to help make your experience better in the future.