Paging with PHP

I trolled around the interwebz for a good 3 hours the other night looking for this.
I wanted to page through my mysql query’s resultset rather than display what could potentially be thousands of records on a single page. I wanted to limit the results per page to a certain, low number and display “Previous/Next Page” links at the end of that limited count.

Although I have to say that such a task is done very simply in asp.NET, I thoroughly enjoyed the challenge of doing it in PHP.

The first thing we need to do is find where the start of the page will be in the resultset. To do this, we pass a value to use in the mysql query. This value will just contain a number to indicate which page we’re on.

$page = $_GET[‘page’];
if (!isset($page)) {
header(‘Location: /mysite/index.php?page=1’);
}

$sql = ‘SELECT * FROM articles LIMIT ‘.($page – 1) * 10.’, 10′;
$result = $dbh->prepare($sql);
$result->execute();

foreach ($result->fetch() as $row) {
// Build each

here to display results.
}

$sql = ‘SELECT COUNT(*) FROM articles’
$result = $dbh->execute($sql);
$count = $result->fetch();

if ($page > 1) {
echo ‘Previous‘;
}
if ($count > $page) {
echo ‘Next‘;
}

The code might not be 100% accurate as I just wrote this off the top of my head. I hope it gives you an idea how to do this anyway.

Good luck!

– L

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s