开发者

Pagination function

I'm trying to make a pagination script made by Jonathan Sampson (gotta give credit for his excellent video tutorials) into a function, so that I don't have to have to write it on every page I want pagination on, so I can use it all over my site without having pagination code on every page :)

I thought I'd pass the query with the function and it works good:

function pagination_query($query, $table = false, $column = false)
{

// Create some variables
$pageNumber = (isset($_GET['page']) && is_numeric($_GET['page'])) ? $_GET['page'] : 1;

// Establish number of results per page
$perPage = 5;

// Establish a padding value
$padding开发者_运维问答 = 3;

// Get Start index of results
$startIndex = ($pageNumber * $perPage) - $perPage;

// Get total number of database entries
$totalCount = "SELECT COUNT(*) as 'Total' FROM $table $column";
$rsCount = mysql_query($totalCount) or die (mysql_error());
$rowCount = mysql_fetch_object($rsCount);

----- non essential stuff removed -----

// Get page results
$sql = "$query 
        LIMIT $startIndex, $perPage";
// Get result set
$query = mysql_query($sql) or die(mysql_error());

return $query;
}

In use:

$query = pagination_query("SELECT id, message 
FROM posts WHERE topicid = 1 
ORDER BY id", 'posts', 'WHERE topicid = 1');


if (mysql_num_rows($query)> 0) {
// Show the results
while($row = mysql_fetch_object($query)) {
print "<div>";
print $row->id;
print ": ";
print substr($row->message, 0, strrpos(substr($row->message, 0, 50), ' ')) . '...';
print "</div>";
} 
}

I just figured out that with this, I can only print the links in one place on the page. Any ideas?

What do you guys think of my solution? Is there a smarter and better way?


You should really use a library specialised on this instead of writing own code. One example is the PEAR Pager.


Pagination in PHP/MySQL is simply attained by using the LIMIT clause.

Initially you have to count the total records and divide it by the records per page.

Pass the page number along with REQUEST.

Read the page number from the REQUEST array and find out the starting record of the page.

You can further read and see the complete implementation on the following page

http://www.csnotes32.com/2014/11/page-wise-or-paginated-listing-of-data.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜