Php paging - How to continue numbering in following pages - php

In my pagination code, I list 5 buildings per page and number them from 1 to 5,
<?php
$page = intval($_GET['page']);
if(!$page) $page = 1;
$totalno=mysql_num_rows(mysql_query("SELECT M1_ID FROM M1Buildings WHERE M1_Cat2 BETWEEN 3 AND 4 && M1_Status=5"));
$limit = 5;
$show = $page * $limit - $limit;
$buildinglist = mysql_query("SELECT * FROM M1Buildings WHERE M1_Cat2 BETWEEN 3 AND 4 && M1_Status=5 ORDER BY M1_Height DESC LIMIT $show,$limit",$con);
$firstrowno=1;//This will be 1 for page 1, 6 for page 2, 11 for page 3 etc..
?>
Some html code here, then:
<?php
$startno=1;//This is the number of each row, starting from 1
while ($rowblist = mysql_fetch_array ($buildinglist))
{
echo '<tr>
<td>'.$startno.'</td>
<td>Some information here</td>
<td>Some information here</td>
</tr>';
$startno++;
$firstrowno+5;
}
?>
There is no problem in first page, but when I pass to page 2, it again starts from 1, but I want it starts from 6, I couldn't get how can I achieve it. I've performed a search, but no result. Actually with my limited english, I can't know how to search it with proper words, I guess. Thanks for your understanding!

You need to update your query to use offset. (** Sorry, didn't notice you were using the shorthand **)
Took a moment for me to get the gist of the question.
Use:
$startno = $show + 1;
instead of:
$firstrowno= 1;
After the HTML:
<?php
while ($rowblist = mysql_fetch_array ($buildinglist))
{
echo '<tr>
<td>'.$startno.'</td>
<td>Some information here</td>
<td>Some information here</td>
</tr>';
$startno++;
}
?>
The variables do not retain their state between trips to the server. (Unless you store them and retrieve them from sessions.

Related

Issue with detecting number of pages based on total results from query

I am creating a page for someone where it will display all orders in the database, limited to 10 per page.
It works to that end, but now the issue is when I try to get a max number of pages using the below code:
$msql = "SELECT * FROM orders";
$mresult = $db->query($msql);
if(is_object($mresult) && $mresult->num_rows > 0)
{
if($mresult->num_rows > 10)
{
$maxpage = $mresult->num_rows / 10 + 1;
}
else
{
$maxpage = 1;
}
}
It won't set the $maxpage variable to anything other than 1 unless there are 20 or more orders in the database.
Right now, I have 11 test orders in the database, so when it divides by 10, it should set max pages to 1, + 1 additional page since there are more than 10 orders.
I have scoured the web looking for a solution, and have came up empty handed. Any thoughts or suggestions?
EDIT:
Added code at bottom of the table the actual orders are displayed for further troubleshooting:
<tr>
<td colspan="2" align="left"><<<< Prev</td>
<td align="center">Page <?php if(isset($_GET['page'])) { echo $_GET['page'] . ' of ' . $maxpage; } else { echo '1 of 1'; } ?></td>
<td colspan="2" align="right">Next >>>></td>
</tr>
Your code is running fine, the problem is your statement, the statement where you are dividing by 10, should be within parenthesis, because that needs to be computed first, then add 1 to it, in your code, addition is being done which equals 11, and then 11/11 = 1;
you probably should wrap it within floor function as well.
if($mresult->num_rows > 10)
{
$maxpage = (floor($mresult->num_rows / 10)) + 1;
}
else
{
$maxpage = 1;
}
Please use below code, I have tested.
$query = "select * from orders";
$history_res = mysql_query($query);
//count records
$totrecords = mysql_num_rows($history_res);
$totpages = ceil($totrecords / 10);
return $totpages;
Implementing the code provided by #Talha, and changing my navigation controls to the following fixed the issue:
<tr>
<td colspan="2" align="left"><<<< Prev</td>
<td align="center">Page <?php echo $page . ' of ' . $maxpage; ?></td>
<td colspan="2" align="right">Next >>>></td>
</tr>

How to display long while/for loop in pagination?

I have a while/for loop with thousands results. Since it contains several fields, I use table to display it. However, with thousands results being displayed at the same time, it will definitely slow down the performance. How can I display it in pagination?
<table>
<?php $count = 1000;
for($a=1;$a<=$count;$a++) { ?>
<tr>
<td><?php echo $a; ?></td>
<td>This is number <?php echo $a; ?></td>
</tr>
<?php $i++;
} ?>
</table>
My only solution without having a DB with the data would be to pass the array key you are on to the next page. For example:
$start = 1;
$end = 1000;
if(isset($_GET['record_number'])){
$start = $_GET['record_number'];
$end = $_GET['record_number'] + 1000;
}
for($a=$start; $a<=$end; $a++){
//code here
}
Other than that, you might consider creating a list of files in a DB engine so you can use the LIMIT parameter.
If the data comes from a database you can limit the result set. If you are using MySQL you use the LIMIT clause. This will allow you to only fetch the specified number of rows.
SELECT title, description FROM posts LIMIT 25
This will only fetch 25 rows. Then if you want to fetch the results after row 25 you can provide an offset. This is done a little different since the offset comes first in the LIMIT clause. Only one argument is provided MySQL assumes its the limit instead. To select the next 50 rows you use.
SELECT title, description FROM posts LIMIT 25, 50
This can be useful to reduce the result set fetched and help increase performance/load times due to a smaller amount of data that needs to be processed.
I hope this can help you, happy coding!
Update
This is a little tutorial in using the LIMIT clause in MySQL
Here is my example, it's similar to the answer from #AnotherGuy
<form method="GET">
<input type="text" name="rowsPerPage">
<?php
for($i = 1; $i+1 < $count/$rowsPerPage; $i++){
echo '<input type="submit" name="page" value="'.$i.'">';
}
?>
</form>
<?php
$begin = (int)$_GET['rowsPerPage']*$_GET['page'];
$take = (int)$_GET['rowsPerPage'];
$sql = "SELECT ... LIMIT {$begin}, {$take}";
?>
It's possible that the code contains "typos", but I hope it will give you new ideas.
I would recommend you to use GET instead of POST. GET will be saved in the URL, in this way, it will be easier to reload the page without losing the page-settings.
www.example.com?rowsPerPage=150&page=2

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

Basic pagination

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>

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'])

Categories