Basic pagination - php

I am not a well-versed programmer so i don't want to use a complicated pagination. Is there an alternative to using a pagination like in my queries can i limit them to say 20 results and then if their are more than 20 results i can show a "next" button and then that button will further load the next results??
I only want "next" to show if there are 20> results? Any help will be appreciated. Thanks.
Code:
$query="SELECT * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "";
$i=0;
while ($i < $num) {
$1=mysql_result($result,$i,"production_full_name");
$2=mysql_result($result,$i,"production_id");
$3=mysql_result($result,$i,"actress");
echo "<br><div id=linkcontain><a id=slink href=$data/actress.php?id=$2>$3</a><div id=production>$1</div></div>";
echo "";
$i++;
}

You could add a limit to your query.
$lower_limit = $results_per_page * $page_number;
$upper_limit = $lower_limit + $results_per_page
..and production_full_name LIKE '%$q%' LIMIT $lower_limit, $upper_limit
Then make a conditional "next page" link
if ($upper_limit > 20) echo 'Next;

You can find many examples searching on google.
http://www.php-mysql-tutorial.com/wikis/php-tutorial/paging-using-php.aspx for example.
You only have to edit $rowsPerPage for amount of results, and if you want further edit on what to get from the DB, the $query.
Includes are not necessary, though.
edit: note the implication of using a $_GET that will have influence on the DB query. You have to be careful to not allow dangerous values in it (mysql injection). In the example of the webpage, it uses ceil, so I believe that it will output 0 for a non numeric value, which is safer.

You can use the PEAR packages.
They are much easier to use similar to the frameworks.
But before you use them you need to check whether the PEAR works on your server or not.
If you are using it locally then there are steps to install the PEAR packages on your local machine. For more instructions to install PEAR.
Click here to view the installation steps.
Once you have installed the PEAR package please follow the instruction to configure the PAGER class.http://www.codediesel.com/php/simple-pagination-in-php/
J

Something like that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
And creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
Not tested.

If your query is set up as
"SELECT SQL_CALC_FOUND_ROWS * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%' LIMIT ".($page*$lpage).",".$lpage
... the next statement can be SELECT FOUND_ROWS() to get the actual number of results.
Don't forget to put mysql_real_escape_string() on those variables.
NEVER use SELECT * with mysql_num_rows; if it's a big table, it will waste a LOT of time.

What you can do is fetch a COUNT(*) of how many rows are in your set of data. Then decide how many items you want per page. $numberOfRows / $itemsPerPage gives you the number of pages. In MySQL, to limit results you use LIMIT X, Y X is the beginning of the range, and Y is the number of items you want to fetch. So to fetch all the items on a page, your query would be LIMIT ($currentPage * $itemsPerPage), $itemsPerPage Then it's up to you, depending on how you want to format your pagination, to write the view logic. Just go from back to front: if the current page is 1, then the previous button is disabled. If the page is not 1, then the current page number is the number of pages from the beginning. If the total number of pages is bigger than the current page, then count from the current page, until the last page (unless you want to cut off the page count at some point)
I use the following method to assist in creating a list of pages, no matter what direction. I could plug in 5 for the current page, and 0 as the goal page, and it would return a list of 5 pages for me to iterate through, in order.
/*
* Generates a list of pages based on the current page to the goal page number
*/
function generatePageList($currentPage, $goal) {
$span = $goal - $currentPage;
$step = abs($span) / $span;
$list = array();
for($x = $currentPage; $x !== $goal;) {
// We want to add the step at the beginning of the loop, instead of
// at the end
// Fixes bug when there are only two pages
$x += $step;
$list[] = $x;
}
return $list;
}

This is more easy way to create pagination of a data
<?php
require_once 'db_connect.php';
$limit = 20;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM employee ORDER BY id ASC LIMIT $start_from, $limit";
$rs_result = mysqli_query($con, $sql);
?>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($rs_result)) {?>
<tr>
<td><?php echo $row["employee_name"]; ?></td>
<td><?php echo $row["employee_salary"]; ?></td>
<td><?php echo $row["employee_age"]; ?></td>
</tr>
<?php
};
?>
</tbody>
</table>
<?php
$sql = "SELECT COUNT(id) FROM employee";
$rs_result = mysqli_query($con, $sql);
$row = mysqli_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$pagLink = "<nav><ul class='pagination'>";
for ($i=1; $i<=$total_pages; $i++){
$pagLink .= "<li><a href='index.php?page=".$i."'>".$i."</a></li>";
};
echo $pagLink . "</ul></nav>";
?>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $total_records;?>,
itemsOnPage: <?php echo $limit;?>,
cssStyle: 'light-theme',
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'index.php?page='
});
});
</script>

Related

limited number of rows in a page

Hi I'm retrieving my data from DB
my data is (pic & name ) when I retrieved them I put them in 4 columns
now I wanna limit the number of rows in each page , I want each page shows three rows only
and if there is more data I want to make it display in next page
my code :
<?php
$items_in_row = 4 ;
$index = 0 ;
?>
<table>
<tr>
<?php
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)){
$index++ ; ?>
<td>
<p>
<img id='g1' src='/<?php echo $row["img"] ;?>' width=130 height=130 onClick='f1()'>
</p>
<p> Name: <?php echo $row['name'] ; ?> </p>
<br>
</td>
<?php if ($index%$items_in_row == 0){ ?>
</tr>
<tr>
<?php }
} ?>
</tr>
</table>
One way to do this is to use the LIMIT() function in SQL, passing in variables that you are storing in the session in PHP. Let's say you want 3 rows of 4 pictures on each page, then you want 12 pictures. So you do something like
select * from pictures LIMIT(0,12)
This returns the first 12 items.
You can do it by just tracking page number. Maybe you have a $page variable in your PHP. If you are on page 2, $page contains 2. Use that to construct a dynamic SQL query with your PHP maybe like this...
$sqlQueryStatement = "select * from pictures LIMIT(". ($page-1)*12 . ", 12)";
What this does is for page 2, it produces the sql statement:
select * from pictures LIMIT(12,12)
See how that works? Now you execute that SQL, and you have the set of results that should be output for page 2.
You can use some further logic to take these basic concepts and run with them...extending them to uses like creating the clickable pagination numbers on the bottom of your results and so forth.
i develop my pagination jobs using the following algorithm:
...1) selecting the results
$page = 1; // what page to show, if you dont know 1 is default.
$maxthingsperpage = 5; // how many things (etc. what you show) per page
$offset = ($page * $maxthingsperpage) - $maxthingsperpage; // db id to start reading
$result = mysql_query("SELECT * FROM things LIMIT ".$offset.",".$maxthingsperpage);
...2) display the things into page
$numrows = mysql_num_rows($result);
$numthingstodisplay = ($numrows > $maxthingsperpage ? $maxthingsperpage : $numrows);
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)) {
... display here without worrying about when to break; num rows are exact
}
you can replace $maxthingsperpage with your $items_in_row

how to add pagination to my web based database using php and mysql

I've come across a problem - but any help would be appreciated.
When I query the database using the results posted from a form, the pagination works initially i.e. for the first 10 records but when I click on the 2 hyperlink of the pagination for the second page of results it loses the $_POST variable and returns to the full data set.
What is the best way of keeping these variables available for the second (and further) pages?
thanks for reply:
still i have a problem, can any one help me please , the below is my complete php file
thanks in advance
<html>
<head>
<link rel="stylesheet" type="text/css"
href="design.css">
</head>
<body>
<?php
include("header.php");
?>
<center>
<div id="content" class="frm">
<a href='admin.php' style='float:left'>Back!</a>
<h2>Search Result</h2>
<br><br>
<?php
include("../config.inc");
$find=$_GET['find'];
// get page no and set it to page variable, if no page is selected so asign first page bydefualt
if (isset($_GET["page"])){
$page = $_GET["page"];
}
else {
$page=1;
}
// count all record in this table then divide it on 10 in order to find the last page----- every page has 10 record display
$sql = "SELECT COUNT(*) FROM tt where TTT='$find' ";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 2);
// this line check that page no must be in integer format
$page = (int)$page;
if ($page > $total_pages) {
$page = $total_pages;
} // if
if ($page < 1) {
$page= 1;
} // if
$start_from = ($page-1) * 2;
$q=mysql_query("select * from tt where TTT='$find' order by ID limit $start_from,2");
$c=mysql_query("select count(*) from tt where TTT='$find'");
echo "<center>".mysql_result($c,0)."Filtered</center>";
echo "<center>";
echo "<table border='2' bgcolor=#CCCCCC>
<tr>
<th>TTT</th>
<th>Enroll Date</th>
<th>Gradution Date</th>
<th>ID</th>
</tr>";
while($row=mysql_fetch_array($q))
{
echo "<tr>";
echo "<td>".$row['TTT']."</td>";
echo "<td>".$row['Enroll_Date']."</td>";
echo "<td>".$row['Graduation_Date']."</td>";
echo "<td>".$row['ID']."</td>";
}
echo "</table>";
echo "<center>";
// paginatio start here
if ($page== 1) {
echo " << < ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?page=1'><<</a> ";
$prevpage = $page-1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$prevpage'><</a> ";
} // if
echo " ( Page [$page] of [$total_pages] ) ";
if ($page == $total_pages) {
echo " > >> ";
} else {
$nextpage = $page+1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$nextpage'>></a> ";
$lastpage=$total_pages;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$lastpage'>>></a> ";
} // if
?>
</div>
</center>
<?php
include("footer.php");
?>
</body>
</html>
The best practice says to not use POST method if your query doesn't alter the state of your system. For example, in your case I wouldn't submit a POST request but I'd use GET.
That way your pagination links should preserve your query parameters.
Don't use POST in the first place. POST is for sending data to be acted on. GET is for sending data that describes what you want to read. If you are paginating, then you are reading things.
Then make sure your links contain all the data you need to describe what it is you want the second (or third or etc) page to contain.
Its usefull to get a pre-written pagination class if you are inexperienced making one yourself. (if not ignore this awnser)
You could use something like this
http://www.catchmyfame.com/2011/10/23/php-pagination-class-updated-version-2/

PHP pagination problem, gives blank page

Below is a code for my pagination. The problem that I am having is that the page count is displayed correctly but when I click on page 2 onwards I just get a blank page.
<?php
if (isset($_POST['edit'])) {
if (empty($_GET['page'])) {
$page=0;
}
else {$page = (int)$_GET['page'];}
if ($page == 0){ $page = 1;}
if (ob_get_level() == 0) ob_start();
$per_page = 10;
$p = ($page - 1) * $per_page;
$sql="select * from tba where word='$word' order by id DESC limit ".$p.",".$per_page;
$result=mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_array($result)) {
$id=$row['id'];
$word=$row['word'];
$pr=$row['pr'];
if ($pr==0) {
}
else {
?>
<td><span class="style5"><?php echo $id; ?> </span></td>
<td><span class="style5"><?php echo $word?></span></td>
<?php
}
$pages = floor($total / $per_page) + ($total%$per_page>0?1:0);
?>
<center>
<?php
}
for ($i=1;$i<=$pages;$i++) {
print "<a href='?page=".$i."'>".$i."</a> ";
}
echo "<br>You are in page ".$_GET['page'];
}
can some one please tell me what the problem is?
It's time to learn debugging.
As a matter of fact, we can only guess what is going wrong.
While it is only programmer oneself who can tell it for sure. It's their job and duty.
The art of finding what is going wrong is called debugging.
To do it, you have to check every operation result.
For example, does your query return any results?
If not - why? Where does that $word variable come from? But on the second page?
You have to pass all required data to other pages as well as $page variable.
It looks like the $pages = floor... line is inside the while loop, which is the first problem. Also, $total is never being set.
The variable $total is never set making the total pages count incorrect
You need to fetch first the total number of rows with a query similar to:
$sql="SELECT COUNT(id) AS rows FROM tba where word='$word'";
Instead of doing the "floor" operation and adding "1" when has "other page" you can use "ceil"
Instead of:
$pages = floor($total / $per_page) + ($total%$per_page>0?1:0);
You can use:
$pages = ceil($total / $per_page);
Well, the whole output is in an if statement and you didn't posted the POST parameters ($_POST['edit'])

How to allow multiple filters to be selected - pagination?

Hey, I am still trying to allow multiple filters to be selected for my pagination script but not sure how to do it being very new to php and programing in general.
So in my pagination, when a user clicks the 'marketing' button(link) it queries the database just for the category that = marketing. The same goes for the other 2 filter buttons as seen in the script below. (automotive, sports).
The problem is, I want to be able to select multiple filters like only marketing and auomotive or automotive and sports, for example if I click the marketing filter and then the automotive, it would display the categories that equal marketing, and automotive.
I have no idea how to accomplish this, so I have come to the experts to help me out.
This is the script I am working on:
<h3>Filter results by:</h3>
<a href='pagi_test.php?category=marketing'>marketing</a>
<a href='pagi_test.php?category=automotive'>automotive</a>
<a href='pagi_test.php?category=sports'>sports</a>
<br />
<h3>Results:</h3>
<?php
//connecting to the database
$error = "Could not connect to the database";
mysql_connect('localhost','root','root') or die($error);
mysql_select_db('ajax_demo') or die($error);
//max displayed per page
$per_page = 3;
//get start variable
$start = $_GET['start'];
$category = mysql_real_escape_string($_GET['category']);
//count records
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='$category'"));
//count max pages
$max_pages = $record_count / $per_page; //may come out as decimal
if (!$start)
$start = 0;
//display data
$get = mysql_query("SELECT * FROM explore WHERE category='$category' LIMIT $start, $per_page");
?>
<table width="800px">
<?php
while ($row = mysql_fetch_assoc($get))
{
// get data
$id = $row['id'];
$site_name = $row['site_name'];
$site_description = $row['site_description'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $site_name; ?></td>
<td><?php echo $site_description; ?></td>
</tr>
<?php
}
//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;
//show prev button
if (!($start<=0))
echo "<a href='pagi_test.php?category=$category&start=$prev'>Prev</a> ";
//show page numbers
//set variable for first page
$i=1;
for ($x=0;$x<$record_count;$x=$x+$per_page)
{
if ($start!=$x)
echo " <a href='pagi_test.php?category=$category&start=$x'>$i</a> ";
else
echo " <a href='pagi_test.php?category=$category&start=$x'><b>$i</b></a> ";
$i++;
}
//show next button
if (!($start>=$record_count-$per_page))
echo " <a href='pagi_test.php?category=$category&start=$next'>Next</a>";
?>
Any help on this would be great. Thank you.
-- EDIT --
If anyone has a better method of doing a pagination system with multiple filters than the one above, please let me know.
While selecting second filter u can add the category
ex:
At first ur variable $category has
$category="Marketing";
When user filter with another category suppose automotive then add it to $category with a delimeter,Now
$category="Marketing:Automotive";
when u access thru GET use explode:
$cat=explode(":",$_GET['category']);
and write your condition
$condition="category=category[0]";
for($i=1; $i<sizeof($cat); $i++)
{
$condition="AND category=$cat[$i]";
}
$where="WHERE $condition";
use $where in ur query, like
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore $where"));
I see two separate issues
How to allow the user to select more than one category to filter by
How to propagate those choices to the pagination links
Each for which I have a solution!
How to allow the user to select more than one category to filter by
A form is going to be the most direct approach.
<h3>Filter results by:</h3>
<form action="pagi_test.php" method="GET">
<input type="checkbox" name="category[]" value="marketing" id="cat_marketing"/>
<label for="cat_marketing">Marketing</label>
<br/>
<input type="checkbox" name="category[]" value="automotive" id="cat_automotive"/>
<label for="cat_automotive">Automotive</label>
<br/>
<input type="checkbox" name="category[]" value="sports" id="cat_sports"/>
<label for="cat_sports">Marketing</label>
<br/>
<input type="submit" value="Filter!" />
</form>
Now, $_GET['category'] will be an array of every category that was selected.
$categories = $_GET['category'];
$inClause = "'" . implode( "','", array_map( 'mysql_real_escape_string', $categories ) ) . "'";
//count records
$record_count = mysql_num_rows(
mysql_query( "SELECT * FROM explore WHERE category IN($inClause)" )
);
Of course, you'd probably want to add a check here to make sure $categories isn't empty before you execute the query.
You'll need to modify the actual selection query as well
//display data
$get = mysql_query("SELECT * FROM explore WHERE category IN($inClause) LIMIT $start, $per_page");
Bingo! Now that part is done!
How to propagate those choices to the pagination links
Since we already have an array of the categories selected stored in $categories, this will be trivial using http_build_query().
//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;
// Get the categories in an HTML-safe array
$requestVars = array_map( 'htmlspecialchars', $categories );
//show prev button
if (!($start<=0))
{
$requestVars['start'] = $prev;
echo 'Prev ';
}
//show page numbers
//set variable for first page
$i=1;
for ( $x = 0; $x < $record_count; $x = $x + $per_page )
{
$requestVars['start'] = $x;
if ( $start != $x )
{
echo ''. $i .' ';
} else {
echo '<b>'. $i .'</b> ';
}
$i++;
}
//show next button
if (!($start>=$record_count-$per_page))
{
$requestVars['start'] = $next;
echo 'Next ';
}
Now, there are still holes in this implementation.
Since the <form> is printed to the page before the rest of the logic, there's no way to pre-select the checkboxes that represent the current filter choices. Which you could definitely change.
Also, you have categories as literal strings in the PHP script - they would really be better in their own table in the database.
The way you retrieve a count for the entire data set is inefficient - it sends the entire data set over the wire to PHP, which then is responsible for determining the record count. It's much better to run a separate query that uses SELECT count(*) ... instead.

How to update sql query dynamically - jquery

I am trying to figure out how I can update my sql query dynamically.
On the main page, I have a pagination script that counts how many pages there will be:
<?php
function generate_pagination($sql) {
include_once('config.php');
$per_page = 3;
//Calculating no of pages
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page);
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li class="page_numbers" id="'.$i.'">'.$i.'</li>';
}
}
?>
I then have in the body of the same page this line of code to populate the page numbers:
<?php generate_pagination("SELECT * FROM explore WHERE category='marketing'"); ?>
So, that line is displaying the necessary amount of page numbers to be displayed for just the 'marketing' category.
The problem that I am having is with that single line of code. I want to make the category dynamic, so instead of it being hardcoded to 'marketing' I would like jquery to get the id of an element and place it in.
The element would be this link that I have on the same page:
Marketing
So, when the user clicks that link, I am trying to place the id of the link in the category section of the query using jquery.
I hope that made sense, and if anyone can assist me on this that would be great.
First, the PHP side:
<?php
function generate_pagination($sql) {
include_once('config.php');
$per_page = 3;
//Calculating no of pages
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page);
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li class="page_numbers" id="'.$i.'">'.$i.'</li>';
}
}
?>
<?php generate_pagination("SELECT * FROM explore WHERE category='" . mysql_real_escape_string ( $_POST ['category'] ) . "'"); ?>
Then in your jquery post:
$("a.category").click(function() {
$.post("test.php", { category: $(this).attr("id") },
function(data){
//Load your results into the page
});
});
On click we take the ID, pass it to the server as a post variable category, then on the server, grab it, escape it properly for security, and use that query. Load your results the same way you are now, that part doesn't change.

Categories