How To Add PHP Pagination To LinkShare Products

by derek on June 16, 2010 · 32 comments

Imagine that you have taken the time to hack your way through adding a long list of products to your online store, or that you heeded my earlier advice and leveraged my tips on how to add affiliate products from LinkShare to your blog or affiliate website. You step back to soak in your brilliance and realize that one long list with hundreds or thousands of products is not very user friendly!
What should you do?
One option would be to leave your monstrosity of products alone, but that will most likely guarantee that you don’t earn any affiliate commissions. A better option is to add some simple PHP pagination code to your product results, which you can see in action over at Chicago football gifts.
With this post, I will explain exactly how the PHP pagination controls can be added to your own site to help you maximize your conversions and affiliate earnings. Prepare yourself for a delightful journey down the road of code snippets and technical details, leading you to the land of more money in your pocket.
Keep in mind that the method I present below is certainly not the only – and likely not even the best – method of accomplishing pagination, but it is what I have implemented in the past and what I will share with you today.

Start Small and Easy

In order to lay the groundwork for our pagination controls, we will first need to add a few additional lines of code to Code Example #2 from our original example.
[php]
if (isset($_GET[‘pg’]))
$pageno = $_GET[‘pg’];
else
$pageno = 1;
if (isset($_GET["rpp"]))
$rows_per_page = $_GET["rpp"];
else
$rows_per_page = 5;
[/php]
The above code simply adds two basic “if / else” statements to check for the existence of two new parameters – pg represents the page number while rpp represents the number of rows per page.
In the event that either parameter has not yet been set, we assign a default value (set to any value of your preference); 1 for the page number and 5 for the number of rows per page respectively.
These new lines of code should be added directly above the original code, as indicated below:
[php]
<?php
*** INSERT NEW CODE HERE ***
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, "http://" . $_SERVER[‘SERVER_NAME’] . "/linkshare.php?keyword=KEYWORD&cat=CATEGORY&max=MAX&pg=".$pageno."&rpp=".$rows_per_page."&mid=MERCHANT");
[/php]
Note: In addition to adding the new lines of code above the original code, we need to add our new parameters to the URL that we built which is shown above on Line 4. You will notice that we added the “pg” and “rpp” parameters to the querystring.
Now that we have the easy part out of the way, we will move on to the…

Meat and Potatoes – PHP Pagination

After providing the code found in the original post (Code Example #1) regarding adding products from LinkShare, I had to change the method used for the parsing of the data due to a few changes in my requirements. The updated code, shown in its entirety below, is using the XML library by Keith Deven.
[php collapse=”false” wraplines=”false”]
<?
include(‘xml.php’);
$url = "http://65.245.193.50/productsearch";
$token = "ADDTOKENHERE"; // Add your LinkShare token here
$keyword = $_GET["keyword"];
$category = $_GET["cat"];
$maxresults = $_GET["max"];
$mid = $_GET["mid"];
$resturl = $url."?"."token=".$token."&"."keyword=".$keyword."&"."cat=".$category."&"."MaxResults=".$maxresults."&"."mid=".$mid;
$data = file_get_contents($resturl);
$xml = XML_unserialize($data);
if (isset($_GET[‘pg’]))
$pageno = $_GET[‘pg’];
else
$pageno = 1;
if (isset($_GET["rpp"]))
$rows_per_page = $_GET["rpp"];
else
$rows_per_page = 5;
if (isset($_GET[‘permLink’]))
$permLink = $_GET[‘permLink’];
else
$permLink = "http://MYDOMAIN.COM";
// Check to see if the XML response was loaded, else print an error
if ($xml)
{
$results = ”;
// If the XML response was loaded, parse it and build links
foreach ($xml as $dataload) {
foreach ($dataload as $maindata) {
if (!is_array($maindata)){ $maindata = array($maindata); }
if (is_array($maindata[0]))
{
$numrows = count($maindata);
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage)
$pageno = $lastpage;
if ($pageno < 1)
$pageno = 1;
$start = ($pageno * $rows_per_page) – $rows_per_page;
$maindata = array_slice($maindata, $start, $rows_per_page);
for ($i = 0; $i < count($maindata); $i++)
{
$link = $maindata[$i]["linkurl"];
$title = $maindata[$i]["productname"];
$imgURL = $maindata[$i]["imageurl"];
$price = "$" . $maindata[$i]["price"];
$merchantname = $maindata[$i]["merchantname"];
$description = $maindata[$i]["description"]["short"];
$results .="<div id=\"product\"><div id=\"product_img\"><a href=\"$link\"><img border=\"0\" src=\"$imgURL\"/></a></div><div id=\"product_link\"><a href=\"$link\">$title</a></div><div id=\"product_desc\">".$description."</div><div id=\"product_price\">Add to Cart: <a href=\"$link\">$price</a></div></div><br/>";
}
}
}
}
}
else
{
$results = "<div id=\"product\">There are no available products at this time.</div>";
}
if ($results == ”) { $results = "<div id=\"product\">There are no available products at this time.</div>"; }
get_paging_links($pageno, $permLink, $lastpage, $rows_per_page);
print $results;
get_paging_links($pageno, $permLink, $lastpage, $rows_per_page);
echo "<br />";
function get_paging_links($pageno, $permLink, $lastpage, $rows_per_page)
{
$prevpage = $pageno-1;
$nextpage = $pageno+1;
echo "<div class=’pagination’>";
if ($rows_per_page == 5) echo " <span class=’disabled’>5 per page</span> "; else echo " <a href=’$permLink?pg=$pageno&rpp=5′>5 per page</a> ";
if ($rows_per_page == 10) echo " <span class=’disabled’>10 per page</span> "; else echo " <a href=’$permLink?pg=$pageno&rpp=10′>10 per page</a> ";
if ($rows_per_page == 15) echo " <span class=’disabled’>15 per page</span> "; else echo " <a href=’$permLink?pg=$pageno&rpp=15′>15 per page</a> ";
echo " <br/><br/>";
if ($pageno == 1) {
echo " <span class=’disabled’>&#9668;&#9668;</span> <span class=’disabled’>&#9668;</span> ";
} else {
echo " <a href=’$permLink?pg=1&rpp=$rows_per_page’>&#9668;&#9668;</a> ";
echo " <a href=’$permLink?pg=$prevpage&rpp=$rows_per_page’>&#9668;</a> ";
} // if
echo " ( Page $pageno of $lastpage ) ";
if ($pageno == $lastpage) {
echo " <span class=’disabled’>&#9658;</span> <span class=’disabled’>&#9658;&#9658;</span> ";
} else {
echo " <a href=’$permLink?pg=$nextpage&rpp=$rows_per_page’>&#9658;</a> ";
echo " <a href=’$permLink?pg=$lastpage&rpp=$rows_per_page’>&#9658;&#9658;</a> ";
} // if
echo "</div>";
}
?>
[/php]
For purposes of this post, I will not provide an in-depth explanation of all the PHP code in the above example but I would like to highlight a few sections pertinent to the PHP pagination controls.
First, you should notice a familiar piece of code that we added to the first section earlier on where we simply check for the existence of the parameters and assign default values if they have not been set.
[php firstline=”17″]
if (isset($_GET[‘pg’]))
$pageno = $_GET[‘pg’];
else
$pageno = 1;
if (isset($_GET["rpp"]))
$rows_per_page = $_GET["rpp"];
else
$rows_per_page = 5;
[/php]
Once we have our result set and we are beginning to loop through the data, we then do a quick check to see if we are dealing with an array of data. Assuming that we are, we then retrieve the total number of rows and use that to calculate the last page as this will change based on the number of rows we will be displaying per page.
We then confirm whether or not the user is on the last page or the first page, before we compute the starting position that determines which item should be displayed first. For instance, if we are on the 2nd page we need to be sure that we start with item #6 as opposed to item #1 from the first page.
Once we have our starting position, we splice the array to return the desired number of items from the array that we can then display to the screen.
[php firstline=”42″]
if (is_array($maindata[0]))
{
$numrows = count($maindata);
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage)
$pageno = $lastpage;
if ($pageno < 1)
$pageno = 1;
$start = ($pageno * $rows_per_page) – $rows_per_page;
$maindata = array_slice($maindata, $start, $rows_per_page);
[/php]
Now that all of the product information has been retrieved and stored into a variable, we will send the results to the screen along with the paging controls. In this piece of code, we will create the paging controls before we display the content and then again after the content has been displayed.
[php firstline=”78″]
get_paging_links($pageno, $permLink, $lastpage, $rows_per_page);
print $results;
get_paging_links($pageno, $permLink, $lastpage, $rows_per_page);
echo "<br />";
[/php]
The final piece of the code is the function that is responsible for actually generating the pagination controls. This function is fairly straightforward, with the primary responsibility to determine what CSS needs to be applied to the various controls based on the current page number and the number of rows per page.
As an example, if the user has selected that they want to view 10 rows per page, we disable the button for “10 Rows” as they don’t have a need to select this button again. Similarly, if the user is on the first page of the search results there is no need for the “Previous” page link to be enabled.

Are You Still Awake?

While I tried not to get too technical with the explanation of the code, I am sure that a number of you have had your eyes glaze over and might even be drooling a little as you sit staring at your monitor in an unresponsive state.
As such, I would be happy to help answer any additional questions or to do my best in providing further clarification as needed.
Please remember, I do not make any claims that the above code examples are the recommended way to implement PHP pagination controls in your own website. This is simply a recap of a method that has worked well for me in the past and is provided to you here as one possible alternative to implement on your own site.
Raise your hand if I lost you after “Start Small And Easy”! 😉

Stay In The Loop!

Subscribe to the Derek Semmler dot com feed via RSS or Email to receive notifications when new posts are published. Follow the WordPress ninja on Twitter too!

{ 32 comments… read them below or add one }

Lindsey June 16, 2010 at 5:23 am

oh man that still sounds hard to do sorry dude! maybe its this AZ heat frying my brain lol

Reply

derek June 16, 2010 at 12:50 pm

It looks harder than it is but I know that a lot of people would disagree with that. Thanks for the feedback.

Reply

ArtMan June 17, 2010 at 12:52 pm

Hi,
Thanks for the GREAT post. I put everything in place, but now I don’t show any products. The out displays ‘No Products Available At Thie Time’ which is the message if the $XML results are empty.
I was able to get your original code to work just fine and I only searched for the keyword (batman in that case) and eliminated other paramters except the token.
The new code doesn’t return any items excep the not available message.
Thank you much.

Reply

derek June 17, 2010 at 3:36 pm

Do you have a link to the page where you have this implemented? I’d be happy to help you get this resolved and get your products displaying along with the pagination controls. There might be something simple that we need to tweak to get your instance running.
Often times debugging something like this is easier if we can chat; you can find me on Yahoo IM as “dsemmler”. I’ve got a few ideas on things to check, such as whether or not you have the xml.php library available on your host and what the query string is from the page initiating the request.
We’ll get you squared away.

Reply

ArtMan June 17, 2010 at 10:35 pm

Hi,
I was able to get the code to work to the point that it now does display products. I wasn’t filling all the parameters. The new code unlike the old code does not filter if one of the link parameters is null. I don’t search by an specific merchant so I ended up puttin the ‘if/else’ statements back to check if requests are not null.
Now the problem that I have is, the paginator fails to pick up the permLink. the value for permLink is null, so it doesn’t paginate.
I’m in Chicago; I’m not sure about your time zone for Yahoo IM. So I left this pot again.
Thank you much for you assistance.

Reply

derek June 17, 2010 at 11:28 pm

I’m in Chicago as well, small world huh!
Okay, I think I know the problem and it is my fault for not updating all of the original code from Example #2. In the code where you’re building the cURL you need to add a parameter to your URL for the permLink similar to the following:
curl_setopt($cURL, CURLOPT_URL, “http://” . $_SERVER[‘SERVER_NAME’] . “/linkshare.php?keyword=KEY&cat=CAT&max=MAX&mid=MERCHANT&pg=”.$pageno.”&rpp=”.$rows_per_page.”&permLink=http://” . $_SERVER[‘SERVER_NAME’] . “/“)
I’m on IM right now if you’re still working. Also, I apologize for excluding some of the null checks in this version. Since I know I am always passing param values I was lazy in my code. 🙂

Reply

ArtMan June 22, 2010 at 8:17 am

Hi,
Sorry for the late response. You are in Chicago also – it sure is a small world! Perhaps we can IM today sometimes. I have more questions for you if you don’t mind.
Thanks again.

derek June 22, 2010 at 3:39 pm

It was great to have an opportunity to connect with you on IM today and chat about things. Funny to learn that the world is even smaller than I thought.
I’m always available for questions, I might not always have the answer but I will do my best to help out.

artman June 17, 2010 at 10:37 pm

by the was the website is http://www.dealschoice.com. It basically is a test site at this poin, untill I get things working.
Thanks.

Reply

jon June 17, 2010 at 5:43 pm

great post thanks! enjoyed reading it.

Reply

derek June 17, 2010 at 11:49 pm

Thanks Jon.

Reply

Plasterers bristol June 21, 2010 at 6:48 am

Yeah, that looks quite hard to do…Will have another read through, see if i can get my head round it

Reply

philip - Online Auction June 25, 2010 at 4:54 am

amazing share, keep it up.

Reply

desktop.ini June 27, 2010 at 3:03 am

looks difficult but i will give it a try for sure…thanq for the nice info

Reply

SQL Training July 12, 2010 at 4:37 am

I do not use LinkShare (Specially because I really did not know about its existence, I am quite a newbie) but I will be trying it out now. And then implementing your Pagination hack.

Reply

kadir avci July 30, 2010 at 4:35 am

Very good share. Thank you. I applied to my blog.

Reply

Master August 1, 2010 at 5:13 pm

great post thanks!
I like your PHP tutorial and found it really very helpfull.

Reply

Frans August 20, 2010 at 9:34 am

Looks very interesting to me, but also very difficult ;). I like it though that you’d like to share this php script with us.

Reply

Hemoriva August 31, 2010 at 3:14 pm

I like your PHP tutorial and found it really very helpfull.

Reply

Adam Haver - Utah Graphic Designer September 9, 2010 at 11:11 am

PHP is really interesting but can be somewhat of a challenge to learn – thanks for the help. Great blog BTW.

Reply

dataminerz September 28, 2010 at 11:09 am

I am new to php. Great instructional information about how different php codes can be used to maximize the benefits.

Reply

Jon January 20, 2011 at 5:35 am

Hi Derek, I made use of your first edition of this script, but used a form to pass the variables to the script so I could have an actual user search. However, that’s part of my problem. I’d like to implement the pagination, but the variables are not being stored. When I perform a search, I get the first page displayed with the default of 5 items, but going to any other page (or changing the rows per page) gives me the “no products found”, indicating my variables aren’t being passed along. I’m not a programmer…just a hack at best, so I’m not real sure how to go about this. Hopefully you can point me in the right direction. Thanks! Jon

Reply

derek January 20, 2011 at 5:48 pm

Jon, first I love the fact that you took the code and tweaked it to fit your needs! That is the great aspect about sharing code with people.
Can you provide a link to where you have this implemented? I will take a look and see if I notice anything. My first thought is that your variables aren’t being passed along…possibly because of a different in POST vs. GET on the querystring?

Reply

Jon January 20, 2011 at 6:43 pm

Thanks for the reply, Derek. Right now, I’m not utilizing the script with any pagination functions, but I will set up a couple of pages tomorrow and drop a link in here for you to take a look. Thanks for the help!

Reply

derek January 20, 2011 at 6:45 pm

Sounds good. Hopefully we will be able to get you up and rockin’ in no time.

Reply

Jon January 21, 2011 at 7:40 am

Hi Derek. I’ve set up a simple search and results page to show you what’s going on here. The only changes I’ve made to the code above were to my token, permalink structure and I also remove the CAT and MID entries as I don’t use them. I also had to change the _GET for keyword and MAX to _POST. If there’s anything else you need, just let me know. I really appreciate the help!

Reply

Jon January 21, 2011 at 7:43 am

Link in comment above doesn’t appear to work for some reason, so here is shortlink for it: http://wp.me/PNNa7-ZX

Reply

derek January 21, 2011 at 4:10 pm

Jon, I will give this a look as soon as possible. I’m hopeful that there will be some free time this weekend when I can take a look. I just don’t want you to think that I’m ignoring you, but there are a lot of spinning plates right now. 🙂

Reply

derek January 21, 2011 at 4:14 pm

Oh, just a quick comment – I’m sure that you are well aware of this but by removing the “mid” (merchant id) you’re opening the query up and you could potentially return products that belong to merchants that have not approved you as an affiliate. Unless of course LinkShare has changed their query to only return merchants to which you belong.
Just wanted to make sure I mentioned it after taking a quick look at your site. (I couldn’t help myself.)

Reply

Jon January 21, 2011 at 6:35 pm

Not a problem…take your time. What is in place is working, but I will definitely take a look at the possibility of an open search. I didn’t notice any coming up that I hadn’t been accepted by, but I will run some less common keywords against it and see what comes up. Thanks!

Reply

Brian Kinkade@elizabeth real estate August 11, 2011 at 9:41 am

I did get my eyes glazed over there for a second. This is definitely a great resource for me. Just bookmarked it. Thanks, Derek!

Reply

larry @ plasterers wandsworth August 30, 2011 at 5:44 am

pretty sweet tips here pal, keep up the work, its scary how long those codes are though

Reply

Leave a Comment

Previous post:

Next post: