Modifing Pagination-Sorting Method to Change Rows Per Page - php

Hi i have a PHP based Pagination and Sorting Method which works fine.
I am able to sort and paginate according to any categories, but having problems when it comes to rows per page.
i have used GET Method to fetch information for pagination and sorting as
if (isset($_GET['rpp'])&& is_numeric($_GET['rpp'])) {
$rowsperpage = mysql_real_escape_string($_GET['rpp']);
}else{
$rowsperpage='5';
}
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$currentpage = (int) mysql_real_escape_string($_GET['page']);
} else {
$currentpage = 1;
}
if (isset($_GET['order']) && in_array($_GET['order'], $order)) {
$orderby = mysql_real_escape_string($_GET['order']);
}else{
$orderby='id';
}
$sortby = '';
if (isset($_GET['sort'])) {
$sortby = mysql_real_escape_string($_GET['sort']);
}else{
$sortby='desc';
}
for pagination i have used following type of url string
echo " <li><a href='$pagename?order=$orderby&sort=$sortby&rpp=$rowsperpage&page=$nextpage'>Next»»</a>
and my mysql query is
$sql2 = "SELECT * FROM internet_security ORDER BY $orderby $sortby LIMIT $rowsperpage OFFSET $offset";
and in html i have used links to sort categories like
id-desc:
id-asc:
title-desc:
title-asc:
**limit rows by**
5
10
20
My question is
every thing is working fine except when i limit row per page via limit rows by - rows get limited to whatever limit(5,10,20) is selected but then if i click pagination every thing goes to its default set value i.e by id and in DESC order with LIMIT of 5.
and if i do it like
id-desc:
id-desc:
id-desc:
then it works but then i must have at least 12 links for full functionality.which is not a standard approach.
what i want is once a limit is set either by default or by sorting options, i shall be able to sort by id title etc.. and paginatin should works along with it.
i hope i made it clear.
please see what i am doing wrong and suggest any possible solution to my approach.

(Upgrading to an answer)
Store $rpp in a $_SESSION variable, updating only if it's present in $_GET:
if ( isset($_GET[ 'rpp'])) $_SESSION['rpp'] = intval($_GET['rpp']);
elseif (!isset($_SESSION['rpp'])) $_SESSION['rpp'] = 5;
Then use $_SESSION['rpp'] in your query:
$sql2 = "
SELECT *
FROM internet_security
ORDER BY $orderby $sortby
LIMIT $_SESSION[rpp] OFFSET $offset
";

Related

Laravel LengthAwarePagination

I am working with laravel's LengthAwarePaginator Class. My problem is that I cannot use
$users = DB::table('users')->paginate(15);
or in other words,larvel's querybuilder or eloquent results. The reason is I have provided user with a frontend where they can create queries dynamically that can as simple as a select query and can be as complicated as queries with multiple joins etc. So I am left with only option of using LengthAwarePaginator. Here is what I have done do far
private function queryWithPagination($queryString,$path,$fieldName = '',$sortOrder = '',$perPage = 100){
$queryString = str_replace(''',"'",$queryString);
$queryString = str_replace('**',"",$queryString);
if(!empty($fieldName) && !empty($sortOrder)){
$queryString .= " ORDER BY '{$fieldName}' {$sortOrder}";
}
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$limit = $perPage +1; // to have pagination links clickable i.e next,previous buttons
$queryString.= " LIMIT {$limit}";
if($currentPage == 1){
$queryString.= " OFFSET 0";
}
else{
$offset = ($currentPage-1)*$perPage;
$queryString.= " OFFSET {$offset}";
}
$path = preg_replace('/&page(=[^&]*)?|^page(=[^&]*)?&?/','', $path);
$result = DB::connection('database')->select($queryString);
$collection = new Collection($result);
//$currentPageSearchResults = $collection->slice(($currentPage - 1) * $perPage, $perPage)->all();
$entries = new LengthAwarePaginator($collection, count($collection), $perPage);
$entries->setPath($path);
//dd($queryString,$result);
dd($entries);
return $entries;
}
As you can see I append LIMIT and OFFSET in the query otherwise, for complex queries the load time was getting greater resulting in bad user experience. The problem with current set up is that the last page is always set to 2 and when I get to second page I cannot browse more results i.e cases where records returned were more than 500 I can still only browse upto page 2. How do I fix this issue where by using limit offset I can still keep browsing all the results until I get to the last page and then disable the pagination links?
made the second parameter to LengthAwarePaginator dynamic as follows in the given code,it solved my problem
$entries = new LengthAwarePaginator($collection, (count($collection)>=101)?$currentPage*$limit:count($collection), $perPage);

Php pagination from Mysql Select * Where; If click on next page number, then displays all rows from Mysql

In input field user enters condition - what data to get from mysql. For example, user wants to get mysql rows where month is October (or 10).
Here I get user input $date_month = $_POST['date_month'];
Then mysql statement and code for pagination
try {
$sql = $db->prepare("SELECT * FROM 2_1_journal WHERE RecordMonth = ? ");
$sql->execute(array($date_month));
foreach ($sql as $i => $row) {
}
$number_of_fetched_rows = $i;
$number_of_results_per_page = 100;
$total_pages = ceil($number_of_fetched_rows / $number_of_results_per_page);
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page -1) * $number_of_results_per_page;
$end = $start + $number_of_results_per_page;
}
else {
$start = 0;
$end = $number_of_results_per_page;
}
}
else {
$start = 0;
$end = $number_of_results_per_page;
}
for ($page_i = 1; $page_i <= $total_pages; $page_i++) {
echo "<a href='__filter_mysql_data.php?page=$page_i'>| $page_i |</a> ";
}
}
So, user enters month (10), script displays all rows where month is 10; displays page No 1. But if user click on other page number, script displays all data from mysql (all months, not only 10)
What I see - when click on other page number, page reloads, that means that values of php variables "dissapears". As understand after page reload $date_month value is not set (has lost/"dissapears") ? How to keep the value? Or may be some better solution for pagination?
Update.
Behavior is following:
1) in input field set month 10 (October);
2) click on button and get displayed data from mysql where month is 10 (October); so far is ok
3) click on page number 2 and get displayed all data from mysql (all months, not only 10 (October))
Tried to use LIMIT however it does not help.
Possibly problem is related with this code
for ($page_i = 1; $page_i <= $total_pages; $page_i++) {
echo "<a href='__filter_mysql_data.php?page=$page_i'>| $page_i |</a> ";
}
When click on $page_i for not understandable (for me) reasons get displayed all (not filtered) data from mysql. If I use LIMIT also get displayed not filtered results from mysql....
Use LIMIT in your query, have a look at the following example , you can try something like :
SELECT
*
FROM
2_1_journal
WHERE
RecordMonth = ?
LIMIT [start_row],[number_of_rows_per_page]
So for example lets say you have 2 pages with 10 rows per page then the LIMIT for the 2 queries (one per page) will be:
1) LIMIT 0,10
2) LIMIT 10,10
You should change your query like this:
SELECT * FROM 2_1_journal WHERE RecordMonth = ? LIMIT = $number_of_results_per_page OFFSET ($page_number*$number_of_results_per_page);
Here you need to calculate the page number also and you should use the limit and offset concept of mysql.

php pagination for search result failing to display

i've just been learning pagination. i'm having trouble getting it to work for search results. it displays the first page correctly with the right number of links but clicking on any of the links (even on the page 1) goes to a blank page.
can somebody please tell me what i'm doing wrong:
The following code is for when the search button is clicked.
<?php
include('includes/connect-db.php');
include('includes/functions.php');
if (isset($_GET['searchbtn'])){
$product=$_GET['products'];
$status=$_GET['ticket_status'];
$order_by=$_GET['order_by'];
$ticket_type=$_GET['ticket_type'];
#check if product has been selected
if ($_GET['products'] == 'select'){
echo '<font class="error">&nbsp Please select a product to search.</font>';
}else{
if ($status == 'All' AND $order_by == 'All' AND $ticket_type == 'All' ){
$page_query="SELECT * FROM tickets WHERE product='$product' ORDER BY created DESC";
}elseif ($ticket_type == 'BOX'){
$page_query="SELECT * FROM tickets WHERE product='$product' AND status='$status' AND pbi <> '-' ORDER BY '$order_by' ";
}elseif ($ticket_type == 'PVR'){
$page_query="SELECT * FROM tickets WHERE product='$product' AND status='$status' AND inc <> '-' ORDER BY '$order_by' ";
}else{
$page_query="SELECT * FROM tickets WHERE product='$product' AND status='$status' ORDER BY created DESC";
}
}#end of else
$results_per_page=3;
$result_set=pagination($results_per_page,$page_query);
$query=$result_set['query'];
$pages=$result_set['pages'];
#SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset. A resource on success or False on Error
if (!empty($query)){
$result = mysqli_query($db,$query) or die( "My query ($query) generated an error: ".mysql_error());
$num_results = mysqli_num_rows($result);
if ($num_results > 0){
displayTicket($result);
if ($pages > 1){
echo '</br>';
for($i=1;$i<=$pages;$i++){
echo ' '.$i.' ';
}
}
}else{
echo "&nbsp No Records found.";
}
}#query string is not empty
}
?>
i have put the pagination code in a separate function:
function pagination($per_page, $pages_query){
include('includes/connect-db.php');
$pagination[]=array();
#total result count
$total_result=mysqli_query($db,$pages_query);
#ceil takes a decimal number and gives the nearest whole number
$total=mysqli_num_rows($total_result);
$pages = ceil($total / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = " LIMIT $start,$per_page";
$query = $pages_query.$query;
$pagination['query'] = $query;
$pagination['pages'] = $pages;
return $pagination;
}
Note: the pagination linking to other pages only fails when i attempt it with the search feature. i have tried it on a page that lists information in a table and the links work fine.
It looks to me like the problem is the information in the link: localhost/test/searchProductForm.php?page=1 tells searchProductForm which page to display, but it doesn't tell it what the search information was. Without that, your search page has no idea what to display. Try changing the pagination link to include all the information that was in the original search link (i.e., your products, ticket_status, order_by, and ticket_type parameters).
I know this is an old thread, but for anyone not able to solve a similar problem with the code used above, it could be to do with the lack of session_start() at the beginning of the document.
I say this because although the code is trying to obtain the session variables passed by the ?page= &products= etc to $_GET statements but they are not being retrieved into the variables from the URL but you need to place the session_start() at the begging of your PHP document to pass the information from the URL to the strings.

How do I get the first and last results from a query?

I am creating a pagination script and I need to get the first and last results in the database query so that I can determine what results appear when the user clicks a page to go to. This is the code that I have at the minute:
// my database connection is opened
// this gets all of the entries in the database
$q = mysql_query("SELECT * FROM my_table ORDER BY id ASC");
$count = mysql_num_rows($q);
// this is how many results I want to display
$max = 2;
// this determines how many pages there will be
$pages = round($count/$max,0);
// this is where I think my script goes wrong
// I want to get the last result of the first page
// or the first result of the previous page
// so the query can start where the last query left off
// I've tried a few different things to get this script to work
// but I think that I need to get the first or last result of the previous page
// but I don't know how to.
$get = $_GET['p'];
$pn = $_GET['pn'];
$pq = mysql_query("SELECT * FROM my_table ORDER BY id ASC LIMIT $max OFFSET $get");
// my query results appear
if(!$pn) {
$pn = 1;
}
echo "</table><br />
Page $pn of $pages<br />";
for($p = 1;$p<=$pages;$p++) {
echo "<a href='javascript:void(0);' onclick='nextPage($max, $p);' title='Page $p'>Page $p</a> ";
}
I think you have few problems there, but I try to tackle them for you. First, as comments say above, you are using code that it vulnerable to SQL injection. Take care of that - you might want to use PDO, which is as easy use as MySQL extension, and will save you from many trouble (like injection).
But to your code, lets go through it:
You should ask DB to get count of the rows, not using mysql function, it's far more effective, so use SELECT count(*) FROM mytable.
For $pages use ceil() as you want all rows to be printed, if you have $max 5 and have 11 rows, round will make $pages 2, where you actually want 3 (last page just contains that last 11th row)
in LIMIT you want to LIMIT row_count OFFSET offset. You can calculate offset from page number, so: $max = row_count but $offset = ($max * $page) - $max. In your code if $get is directly the page, it means you get $get'th row (Not sure though what happens in your JS nextpage. Bare in mind that not all use JavaScript.)
I have prepared simple example here which uses PDO, maybe that gives you idea how simple it's use PDO.
The selecting rows shows example how to put parameters in SQL, it would be perfectly safe in this case state, 'SELECT * FROM pseudorows LIMIT '.$start.','.$max by I wanted to make an example how easy it is (and then safe):
// DB config
$DB_NAME = 'test';
$DB_USER = 'test';
$DB_PASSWD = 'test';
// make connection
try {
$DB_CONN = new PDO("mysql:host=localhost;dbname=".$DB_NAME, $DB_USER, $DB_PASSWD);
$DB_CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e);
}
// lets say user param 'p' is page, we cast it int, just to be safe
$page = (int) (isset($_GET['p'])?$_GET['p']:1);
// max rows in page
$max = 20;
// first select count of all rows in the table
$stmt = $DB_CONN->prepare('SELECT count(*) FROM pseudorows');
$stmt->execute();
if($value = $stmt->fetch()) {
// now we know how many pages we must print in pagination
// it's $value/$max = pages
$pages = ceil($value[0]/$max);
// now let's print this page results, we are on $page page
// we start from position max_rows_in_page * page_we_are_in - max_rows_in_page
// (as first page is 1 not 0, and rows in DB start from 0 when LIMITing)
$start = ($page * $max) - $max;
$stmt = $DB_CONN->prepare('SELECT * FROM pseudorows LIMIT :start,:max');
$stmt->bindParam(':start',$start,PDO::PARAM_INT);
$stmt->bindParam(':max', $max,PDO::PARAM_INT);
$stmt->execute();
// simply just print rows
echo '<table>';
while($row = $stmt->fetch()) {
echo '<tr><td>#'.$row['id'].'</td><td>'.$row['title'].'</td></tr>';
}
echo '</table>';
// let's show pagination
for($i=1;$i<=$pages;$i++) {
echo '[ '.$i.' ]';
}
}
mysql_fetch_array returns an associative array
Which means you can use reset and end to get the first and last results:
$pqa = mysql_fetch_array($pq);
$first = reset($pqa);
$last = end($pqa);
I don't see how you plan to use the actual results, just page numbers should be sufficient for pagination.
Still, hope it helps. And yes, upgrade to mysqli, so your code doesn't get obsolete.

MySQL PHP Pagination

Is it possible to create pagination without getting all elements of table?
But with pages in GET like /1 /666…
It usually involves issuing two queries: one to get your "slice" of the result set, and one to get the total number of records. From there, you can work out how many pages you have and build pagination accordingly.
A simply example:
<?php
$where = ""; // your WHERE clause would go in here
$batch = 10; // how many results to show at any one time
$page = (intval($_GET['page']) > 0) ? intval($_GET['page']) : 1;
$start = $page-1/$batch;
$pages = ceil($total/$batch);
$sql = "SELECT COUNT(*) AS total FROM tbl $where";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$total = $row['total'];
// start pagination
$paging = '<p class="paging">Pages:';
for ($i=1; $i <= $pages; $i++) {
if ($i==$page) {
$paging.= sprintf(' <span class="current">%d</a>', $i);
} else {
$paging.= sprintf(' %1$d', $i);
}
}
$paging.= sprintf' (%d total; showing %d to %d)', $total, $start+1, min($total, $start+$batch));
And then to see your pagination links:
...
// loop over result set here
// render pagination links
echo $paging;
I hope this helps.
Yes, using mySQL's LIMIT clause. Most pagination tutorials make good examples of how to use it.
See these questions for further links and information:
How do you implement pagination in PHP?
Searching for advanced php/mysql pagination script
more results
You can use LIMIT to paginate over your result set.
SELECT * FROM comments WHERE post_id = 1 LIMIT 5, 10
where LIMIT 5 means 5 comments and 10 is the offset. You can also use the longer syntax:
... LIMIT 5 OFFSET 10

Categories