I have a table that pulls tickets from a MYSQL database and displays them to the user. This part works wonderfully! But, once the user gets 5-10 tickets, the page becomes long and ugly. I am wanting to paginate the responses automatically to show maybe 5 tickets per page and show the rest on following pages.
I am using Bootstrap and have the following for the display of the pagination. "Although I fear this is only pseudo code" I added id's to each main element.
<ul class="pager" id="pagerUL">
<li class="previous" id="previousUL">
← Previous
</li>
<li class="next" id="nextUL">
Next →
</li>
</ul>
Essentially the only code used to pull the database information on the page is:
<?php if(count($tickets) > 0) : ?>
<?php foreach ($tickets as $ticket): ?>
//table content
<?php endforeach ?>
<?php else : ?>
<tr>
<td colspan="7">No Tickets Created.</td>
</tr>
<?php endif; ?>
I thought we could add something to the <?php if(count($tickets) > 0) : ?> But honestly, I am not sure as I am not a expert at php and never even attempted or had the need to build pagination up until now. Any help, guidance, thoughts would be appreciated.
Pass the page number thru the URL and then grab it via php with $_GET.
$page = $_GET['page'];
$per_page = 10; // Define it as you please
$start = $page*$per_page;
$query = "SELECT * FROM table LIMIT ".$start.", ".$per_page;
$result = mysql_query($query);
$count = mysql_num_rows($result);
$i = 0;
for($i=0;$i<$count;$i++)
{
//echo out what you want
echo "";
}
$total_pages = ceil($count/$per_page);
for($i=0;$i<$total_pages;$i++)
{
if($page != $i)
{
echo "<a href='/page.php?page=".$i."'>".$i."</a>";
} else
{
echo $i;
}
}
Related
A form showing different posts of user. Posts which is stored in database. Now the problem is the previous pagination works fine but the next pagination is incrementing 2 blank pages and url changes with that page. Can anyone tell me whats wrong with this code .?
php:
<?php
$limitr = ((($page*2)+1)-2)*$perpage;
$query = mysqli_query($dbc, "SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$limitr}, {$perpage}");
$records = mysqli_fetch_all($query);
$total = mysqli_query($dbc, "SELECT FOUND_ROWS() as total");
$total = mysqli_fetch_assoc($total)['total'];
$pages = ceil($total/$perpage);
?>
<?php
if($page>1){
?>
<a class="page-link" href="?page=<?php $pagep = $page -1; echo $pagep; ?>" tabindex="-1">Previous</a>
<?php
}
?>
</li>
<li class="page-item">
<?php
if($page<$pages){
?>
<a class="page-link" href="?page=<?php $pagen = $page +1; echo $pagen; ?>">Next</a>
<?php
}
?>
"SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$limitr}, {$perpage}");
The first parameter after the LIMIT the offset,, the second is how much records do you want.
But I'm not sure what are you calculating with limitr btw. If you already have which page do you want, it should be simply
LIMIT {($page-1)*perpage}, {$perpage}
Also, the database is unordered, so might miss some records or duplicate others, might wanna add some kind of ORDER BY option.
(SORRY, ORDERS ARE REVERSED WHEN USED WITH COMMA!)
I am writing PHP script to display data from the database (Mysql) on my webpage. I don't want all the information to display on a single page to avoid scrolling. However, I want to display only a few and then use page numbers to navigate to the rest. I managed to create the page numbers and yet still all the information is showing on a single page. Below is my code:
<?php
include('./includes/DB_Config.php');
$status = 1;
// Set number of Post per page for navigation
$post_per_page = 2;
if (isset($_GET['page']))
{
$startP = ($_GET['page'] - 1) * $post_per_page;
}
else
{
$startP = 0;
}
$post = mysqli_query ($mySQL_Conn, "SELECT * FROM BlogPost WHERE status = '$status'");
// Fetch Data or number of rows
$dataRw = mysqli_num_rows($post);
$pages = $dataRw / $post_per_page;
if ($dataRw == 0)
{
$_SESSION['NoPost'] = "No Post Found!";
}
else
{
unset($_SESSION['NoPost']);
//$pages = ceil($dataRw / $rows_per_page);
//$pages = array_slice($dataRw, $startP, $post_per_page);
while ($data = mysqli_fetch_array($post)) //Fetch data in array
{
//Assign data to variabes
$name = $data['blogger_Name'];
$postDate = $data['dateTime'];
$blogpost = $data['blog_message'];
$date = strtotime($postDate);
?>
<p> <span><?php echo $_SESSION['NoPost'] ; ?> </span></p>
<p> <span>By:</span><?php echo $name; ?> </p>
<p> <span>Posted On: </span> <?php echo date("j F Y", $date); ?> </p>
<p> <span>Post: </span><?php echo $blogpost; ?> </p>
<?php
}
}
?>
<hr>
<?php
for ($currentpage = 0; $currentpage < $pages; $currentpage++ )
{
?>
<span> <?php echo $currentpage + 1; ?> </span>
<?php
}
?>
What you are trying to accomplish is a very common pattern, and it's called pagination.
You can use LIMIT and OFFSET in your mysql queries to get only a certain subset of the data, and you can use this for basic pagination.
For example, if you want to display 50 results per page, and the user is on the third page, you set LIMIT to 50 and OFFSET to 2*50 (100), keep in mind the first page is an offset of 0 so we subtract the page by one.
You can use the following sql query to get a subset of data for a specific page.
"SELECT * FROM Users LIMIT $num_results OFFSET ".(($page_num-1)*$num_results);
You can get the total number of possible pages by getting the total row count from the Users table and dividing it by $num_results. A good idea might be to have your output script take a GET url query parameter that will be used as the page number.
I am trying to filter details using a-z list, which I can do successfully.
But the problem I am facing is that when I want to display the result along with some pagination, it doesn't do exactly what I want it to do.
Here is my code:
<?php
session_start();
//what page are we currently on
if(!isset($_GET['page'])){
$page=1;
}
else {
$page=(int)$_GET['page'];
}
//select how many records to show per page
$limit=16;
//count how many rows
$total=$conn->query("SELECT COUNT(*) FROM `movie`")->fetchColumn();
//how many pages will be there
$pages=ceil($total/$limit);
if($page<1){
$page=1;//forcing page to be 1 if it is less then 1
}
else if($page>$pages){
$page=$pages;
}
//calculate the offset
$offset=($page-1)*$limit;
if(isset($_GET['word'])){
$qname=$_GET['word'];
}
else {
$qname='a';
}
$sql=$conn->prepare("SELECT * FROM `movie` WHERE `title` LIKE '$qname%' ORDER BY `movie_id` LIMIT $limit OFFSET $offset");
$sql->execute();
$sql->rowCount();
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$title=$row['title'];
$poster=$row['poster'];
echo '<li><a href="#">
<img src="'.$poster.'" />
<h2><strong>Watch '.$title.' Online</strong></h2>
</a>
</li>';
}
?>
Then somewhere in my html i have this pagination
<?php
$prev=$page-1;
$next=$page+1;
$previous="";
$nextr="";
if($page>1){
$previous='<li>«</span>';
}
if($page<$pages){
$nextr='<li>»</span>';
}
$numbers="";
if($pages>1){
for($i = max(1, $page - 5); $i <= min($page + 5, $pages); $i++){
if($i==$page){
$numbers.='<li><a class="active" href="?page='.$i.'">'.$i.'</a></span></li>';
}
else {
$numbers.='<li>'.$i.'</span></li>';
}
}
}
echo $previous;
echo $numbers;
echo $nextr;
?>
And my html :-
<div class="result"><h2>Browse By Words :- A | B</h2></div>
So when I click on link-a it displays the result and the url is like a-z.php?word=a and then when i try to paginate the url changes to a-z.php?page=2
So, how can I paginate the result after fetching it from the db?
I am looking for a way without ajax.
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/
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.