Paging using PHP and MySQL
Posted by Mohammad Sajjad Hossain on March 9th, 2008
I have coded a class for paging, you may find it here.
### Code for Paging Starts ### //index no of the page $pageIndex = ((int)$_REQUEST['pageIndex'] == 0) ? 1 : (int)$_REQUEST['pageIndex']; //number of rows $rowPerPage = 10; //counting total number of rows $sql = 'SELECT COUNT(*) FROM {your_table_name} WHERE {IF ANY CONDITION}'; $query = mysql_query($sql, $link_identifier); $row = mysql_fetch_row($query); // total records $totalRecords = $row[0]; // number of pages $totalPages = ceil($totalRecords/$rowPerPage); if($pageIndex > $totalPages) { $pageIndex = $totalPages; } $startIndex = ($pageIndex - 1) * $rowPerPage; if($totalRecords > $rowPerPage) { $endIndex = $startIndex + $rowPerPage; } else { $endIndex = $totalRecords; } if($pageIndex == $totalPages) { if($totalRecords > $totalPages * $rowPerPage) { $endIndex = $totalRecords; } } if($totalRecords > 0) { $rangeStart = $startIndex+1; if(($totalRecords > $rowPerPage) || ($pageIndex == $totalPages)) { $rangeEnd = $totalRecords; } else { $rangeEnd = $endIndex; } $range = 'Showing ' . $rangeStart.' - '.$rangeEnd.' of '.$totalRecords; } // link for next page $nextLink = 'page_name.php?pageIndex='.($pageIndex - 1); // link for previous page $previousLink = 'page_name.php?pageIndex='.($pageIndex - 1); // fetching data using pagination $sql = "SELECT * FROM {your_table_name} WHERE {IF ANY CONDITION} LIMIT $startIndex, $rowPerPage"; $query = mysql_query($sql, $link_identifier); ### Code for Paging Ends ###
Now use the resource ‘$query’ and do what you want to do.
April 24th, 2008 at 11:23 pm
[...] on my last post on paging using PHP and MySQL, I have coded this class. It is very easy to implement and it will save your time. Here is a code [...]