php pagination, something wrong - php

Some code from me.
$files = glob("pardod/*.html");
$record_count = 5;
$total_pages = ceil(count($files)/$record_count);
$page = $_GET['page'];
$offset = ($page-1)*$record_count;
$files_filter = array_slice($files, $offset,$record_count);
for ($i = 0; $i<$filecount; $i++){
if ($page){
$start = ($page - 1) * $record_count;
}else{
$start = 0;
}
}
if($total_pages > 1){
if($page != 1){
echo 'Atpakal';
}
if($page != $total_pages){
echo 'Uz priekšu';
}
}
The php pagination dont work, i am just learning how to make, where is a problem?
The *.html files didn't shows :(

Try this code for pagination
<?php
$con=mysql_connect("localhost","root","");
$page=$_REQUEST['page'];
if ($page < 1)
{
$page = 1;
}
$resultsPerPage =15;
$startResults = ($page - 1) * $resultsPerPage;
$numberOfRows = mysql_num_rows(mysql_query('SELECT * FROM tablename'));
$totalPages = ceil($numberOfRows / $resultsPerPage);
echo"<center><table border='1' bordercolor='blue' height='90%' width='90%'> <tr><th bgcolor='silver'>Name</th><th bgcolor='silver'>Password</th><th bgcolor='silver'>Question</th><th bgcolor='silver'> Answer</th><th bgcolor='silver'>Image</th> </tr>";
$i=1;
$result= mysql_query("SELECT * FROM password LIMIT $startResults, $resultsPerPage");
while($row=mysql_fetch_array($result))
{
}
echo"</tr></table></center>";
echo '<center>First&nbsp';
if($page > 1)
echo 'Back&nbsp';
for($i = 1; $i <= $totalPages; $i++)
{
if($i == $page)
echo '<strong>'.$i.'</strong>&nbsp';
else
echo ''.$i.'&nbsp';
}
if ($page < $totalPages)
echo 'Next ';
echo 'Last</center>';
?>

Try This Code
$limit = ( isset($_GET['limit'])) ? $_GET['limit'] : 5;
if (strtolower($limit) == 'all') {
$limit = 'all';
} else {
$limit = filter_var($limit, FILTER_SANITIZE_NUMBER_INT);
if (trim($limit) == '') {
$limit = 5;
}
}
$page = ( isset($_GET['page'])) ? $_GET['page'] : 1;
$page = filter_var($page, FILTER_SANITIZE_NUMBER_INT);
$links = ( isset($_GET['links'])) ? $_GET['links'] : 1;
$links = filter_var($links, FILTER_SANITIZE_NUMBER_INT);
Here is the link where step by step described all the process in details.
Simple Pagination in PHP By Learning Ocean Team

if you are using bootstrap, you can use the following
function pagination($page, $count) {
global $options;
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$actual_link = trim(str_replace("page=".$page, "", $actual_link), "&");
$lenght = ceil($count/$options->get("result_per_page"));
if ($page <= 3) {
if ($lenght < 5) {
$first = 0;
$last = $lenght-1;
} else {
$first = 0;
$last = 4;
}
} else if ($page < ($lenght-2)) {
$first = $page-2;
$last = $page+2;
} else if ($page <= $lenght) {
$first = $page-5;
$last = $lenght-1;
}
if ($page > 0) {
$prev = $page-1;
$next = $page+1;
} else {
$prev = 0;
$next = $page+1;
}
echo '<span>Viewing page '.($page+1).' of '.$lenght.'</span><br>';
echo '<nav aria-label="Page navigation example">';
echo '<ul class="pagination justify-content-center">';
if ($prev > 0) {
echo '<li class="page-item"><a class="page-link" href="'.$actual_link.'&page=0">««</a></li>';
echo '<li class="page-item"><a class="page-link" href="'.$actual_link.'&page='.$prev.'">«</a></li>';
}
for ($i = $first; $i<=$last; $i++) {
if ($i == $page) {
$active = ' active';
} else {
$active = '';
}
echo '<li class="page-item'.$active.'"><a class="page-link" href="'.$actual_link.'&page='.$i.'">'.($i+1).'</a></li>';
}
if ($next < $last) {
echo '<li class="page-item"><a class="page-link" href="'.$actual_link.'&page='.$next.'">»</a></li>';
echo '<li class="page-item"><a class="page-link" href="'.$actual_link.'&page='.($lenght-1).'">»»</a></li>';
}
echo '</ul>';
echo '</nav>';
}
to call the function
$pageNumber = 1;
$totalRowCount = 5000;
pagination($pageNumber, $totalRowCount);

Related

Bootstrap Pagination Questions

I have my website that I converted to bootstrap and all is well but pagers. The system my site uses now in functions.php
function pager($rpp, $count, $href, $opts = array())
{
global $language, $btit_settings;
$pager_type = "new";
if($btit_settings["fmhack_pager_type_select"] == "enabled")
$pager_type = $btit_settings["pager_type"];
if($pager_type == "new")
{
$pages = ($rpp == 0)?1:ceil($count / $rpp);
if(!isset($opts['lastpagedefault']))
$pagedefault = 1;
else
{
$pagedefault = floor(($count - 1) / $rpp);
if($pagedefault < 1)
$pagedefault = 1;
}
$pagename = 'pages';
if(isset($opts['pagename']))
{
$pagename = $opts['pagename'];
if(isset($_GET[$opts['pagename']]))
$page = max(1, intval($_GET[$opts['pagename']]));
else
$page = $pagedefault;
}
elseif(isset($_GET['pages']))
{
$page = max(1, intval(0 + $_GET['pages']));
if($page < 0)
$page = $pagedefault;
}
else
$page = $pagedefault;
$pager = '';
if($pages > 1)
{
$pager .= "\n".'<form name="change_page'.$pagename.'" method="post" action="index.php">'."\n".'<select class="drop_pager" name="pages" onchange="location=document.change_page'.$pagename.
'.pages.options[document.change_page'.$pagename.'.pages.selectedIndex].value" size="1">';
for($i = 1; $i <= $pages; $i++)
$pager .= "\n<option ".($i == $page?'selected="selected"':'')."value=\"$href$pagename=$i\">$i</option>";
$pager .= "\n</select>";
}
$mp = $pages; // - 1;
$begin = ($page > 3?($page < $pages - 2?$page - 2:$pages - 2):1);
$end = ($pages > $begin + 2?($begin + 2 < $pages?$begin + 2:$pages):$pages);
if($page > 1)
{
$pager .= "\n <ul class=\"pagination\"><li> «</li>></ul>";
$pager .= "\n<ul class=\"pagination\"><li>< </li></ul>";
}
if($count)
{
for($i = $begin; $i <= $end; $i++)
{
if($i != $page)
$pager .= "\n <ul class=\"pagination\"><li>$i</li></ul>";
else
$pager .= "\n <li class=\"active\">$i</li>";
}
if($page < $mp && $mp >= 1)
{
$pager .= "\n <ul class=\"pagination\"><li> ></li></ul>";
$pager .= "\n <ul class=\"pagination\"><li> »</li></ul>";
}
$pagertop = "$pager\n</form>";
$pagerbottom = str_replace("change_page", "change_page1", $pagertop)."\n";
}
else
{
$pagertop = "$pager\n</form>";
$pagerbottom = str_replace("change_page", "change_page1", $pagertop)."\n";
}
$start = ($page - 1) * $rpp;
if($pages < 2)
{
// only 1 page??? don't need pager ;)
$pagertop = '';
$pagerbottom = '';
}
return array(
$pagertop,
$pagerbottom,
"LIMIT $start,$rpp");
}
Is there a easy way or plugin i can use to incorporate bootstraps?
Here is sample from a page requests.php
list($pagertop,$pagerbottom,$limit) = pager(intval($btit_settings['req_page']),$count,$dir);
then sets it to a tag
$requeststpl->set("bottom_pager",$pagerbottom);
$requeststpl->set("top_pager",$pagertop);
which is then used as a tag to display it via the requests.tpl
<tag:bottom_pager />
<tag:top_pager />
I just want to have it so it looks like bootstrap style..... but comes out like this....
SAMPLE
SAMPLE2

php pagination should start from 1 not 0

This is my function to download and paginate data from xml file.
<?php
function get_feed_posts($link) {
if(!isset($_GET['page'])) {
$_GET['page'] = 0;
}
$startPage = $_GET['page'];
$perPage = 13;
$currentRecord = 0;
$xml = new SimpleXMLElement($link, 0, true);
foreach($xml->results->result as $item) {
$currentRecord += 1;
if($currentRecord > ($startPage * $perPage) && $currentRecord < ($startPage * $perPage + $perPage)) {
?>
<li><a class="go-to" href="<?php echo $item->click_url;?>" title="<?php echo $item->name;?>">Go to store</a></li>
<?php
}
}
for ($i = 0; $i <= ($currentRecord / $perPage); $i++) {
$n=$i+1;
echo("<a href='?page=".$n."'>".$n."</a>");
}
} ?>
This code works great. But I want to have my pages starting from ?page=1, now this code starts from ?page=0
What about this?
<?php
function get_feed_posts($link) {
if(!isset($_GET['page'])) {
$_GET['page'] = 1; // changed this line
}
$startPage = ($_GET['page'] < 1) ? 0 : $_GET['page'] - 1; // changed this line
$perPage = 13;
$currentRecord = 0;
$xml = new SimpleXMLElement($link, 0, true);
foreach($xml->results->result as $item) {
$currentRecord += 1;
if($currentRecord > ($startPage * $perPage) && $currentRecord < ($startPage * $perPage + $perPage)) {
?>
<li><a class="go-to" href="<?php echo $item->click_url;?>" title="<?php echo $item->name;?>">Go to store</a></li>
<?php
}
}
for ($i = 0; $i <= ($currentRecord / $perPage); $i++) {
$n=$i+1;
echo("<a href='?page=".$n."'>".$n."</a>");
}
} ?>
Notice that any x in ?page=x smaller than 1 will be treated as 0, but you could do better (throw an error? redirect to ?page=1?).

PHP pagination page zero issue

My pagination is showing a page zero (0) when you go to page 2. Not sure why. I don't want to show a page zero.
I'll try to only show the necessary code.
Here is my code:
<?php
$rec_limit = 100;
$targetpage = "dispatch.php";
if (isset($_GET['page']))
{
$page = $_GET['page'];
$offset = $rec_limit * ($page - 1);
}
else
{
$page = 1;
$offset = 0;
}
*** $left_rec = countRecords() - ($page * $rec_limit); ***
$total_records = countRecords(); // countRecords() should be self-explanatory
$total_pages = ceil($total_records / $rec_limit); // $rec_limit is 100
$adjacents = 2;
$previousPage = $page - 1;
$nextPage = $page + 1;
$querystring = "";
$start = ($page < $adjacents ? 1 : $page - $adjacents); // <-- i think the issue is here
$beginning = 1;
$end = ($page > $total_pages - $adjacents ? $total_pages : $page + $adjacents);
foreach ($_GET as $key => $value)
{
if($key != "page") $querystring .= "$key=$value&";
}
echo "<div class="row-fluid"><div class="span2"><ul class="pager"><li>First</li>";
if ($left_rec < $rec_limit)
{
$last = $page - 1;
echo #"<li>Previous</li>";
for($i= $start; $i <= $end; $i++)
{
echo "<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
}
else if($page == 0)
{
for($i= $start; $i <= $end; $i++)
{
echo "<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
echo "<li>Next</li>";
}
else if ($page > 0)
{
$last = $page - 2;
echo "<li>Previous</li> ";
for($i= $start; $i <= $end; $i++)
{
echo #"<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
echo "<li>Next</li>";
}
echo "<li>Last</li>";
echo '</ul></div></div>';
?>
I would really appreciate the help in removing page 0 from the application. Please disregard any typos or missing quotes. The code works with the exception of it showing page 0.
I added a picture of what the application showing page 0. It only shows page 0 when I go to page 2. After that, I no longer see page 0.
Please let me know what I have to do.
Thanks.
Some advice:
You really shouldn't suppress errors using #, instead you should be instantiating all of your variables and writing proper code.
Don't hard-code pagination into each page. Instead, wrap it in a reusable function.
Example:
// draws a menu for navigating multiple pages of content
function paginate($page, $display, $total) {
if(isset($_SERVER['QUERY_STRING']) && trim($_SERVER['QUERY_STRING']) != '') {
if(stristr($_SERVER['QUERY_STRING'], 'page=')) {
$query = '?' . preg_replace('/page=\d+/', 'page=', $_SERVER['QUERY_STRING']);
} else {
$query = '?' . $_SERVER['QUERY_STRING'] . '&page=';
}
} else {
$query = '?page=';
}
$pages = $total <= $display ? 1 : ceil($total / $display);
$self = htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'utf-8');
$first = 'first';
$prev = 'prev';
$next = 'next';
$last = 'last';
echo '<p>';
echo ($page > 1) ? "$first | $prev |" : 'first | prev |';
echo '(page ' . $page . ' of ' . $pages . ')';
echo ($page < $pages) ? "| $next | $last" : '| next | last';
echo '</p>';
}
// output example
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$display = 100;
$start = $display * $page - $display;
$total = countRecords($start, $display);
paginate($page, $display, $total);
I agree with #mister martin, but if you use this code fundamentally, try to change
$start = ($page < $adjacents ? 1 : $page - $adjacents);
To:
$start = ($page < $adjacents ? $page : $page - $adjacents);
Edited: maybe problem in undefined $left_rec, check demo. You can change $s like $_GET['page'] and as I see all works correctly.
Demo.
<?php
$rec_limit = 100;
$targetpage = "dispatch.php";
$total_records = countRecords();
// Nav part
$page = intval($_GET['page'])? $_GET['page']: 1;
$offset = $rec_limit * ($page - 1);
$total_pages = ceil($total_records / $rec_limit); // $rec_limit is 100
$adjacents = 2;
$previousPage = $page - 1;
$nextPage = $page + 1;
$start = ($page < $adjacents ? $page : $page - $adjacents); // <-- I think the issue is this line
$beginning = 1;
$end = ($page > $total_pages - $adjacents ? $total_pages : $page + $adjacents);
$uri = $_GET;
unset($uri['page']);
$querystring = http_build_query($uri);
echo '<div class="row-fluid"><div class="span2"><ul class="pager"><li>First</li>';
if($left_rec < $rec_limit && ($page > 1))
{
echo "<li>Previous</li>";
for($i= $start; $i <= $end; $i++)
{
echo "<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
} else if ($page > 1)
{
echo "<li>Previous</li> ";
for($i= $start; $i <= $end; $i++)
{
echo "<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
echo "<li>Next</li>";
} else {
for($i= $start; $i <= $end; $i++)
{
echo "<li " . ((($page)==$i)? "class=\"active\"" : "") . ">$i</li>";
}
echo "<li>Next</li>";
}
echo "<li>Last</li>";
echo '</ul></div></div>';
?>

PHP question pagination

How would I do so that the page I'm on won't be clickable?
$page = (isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1);
$limit = ($page - 1) * 15;
$sql = mysql_query("SELECT * FROM log LIMIT $limit, 15");
$totalres = mysql_result(mysql_query("SELECT COUNT(id) AS tot FROM log"),0);
$totalpages = ceil($totalres / 15);
for ($i = 1; $i <= $totalpages; $i++) {
$pagination .= "$i ";
}
<p><?php echo $pagination ?></p>
if ($i == $page)
$pagination .= "$i ";
else
$pagination .= "$i ";
Just need to modify the for loop to check what the current page is.
for ($i = 1; $i <= $totalpages; $i++)
{
if ($i != $page)
$pagination .= "$i ";
else
$pagination .= " " . $i . " ";
}
With an if inside the for,
if ( $i != $page) {
//Your code.
}
else
{
//Same page.
$pagination .= " " . $page . " "
}
#RedBlueThing Has soon has I saw your post I got it to work, although I got the idea from a different stackoverflow question with a little modifying of the code.
<?php
echo "<section>";
$link = mysqli_connect("localhost", "root", "root", "user_db");
$page = (isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1);
$offset = 4;
$x = 5;
$limit = ($page - 1) * $offset;
$sql = mysqli_query($link,"SELECT * FROM cfp_blogs;");
$totalres = mysqli_num_rows($sql);
$totalpages = ceil($totalres / $offset);
$stmt = mysqli_query($link, "SELECT * FROM blogs LIMIT $limit, $offset;");
if($stmt->num_rows > 0){
while($obj = mysqli_fetch_object($stmt)) {
echo "<h1>$obj->title</h1>";
echo "<p>$obj->content</p>";
$stmt2 = $link->query("SELECT COUNT(id) AS Tot FROM blogs");
if($stmt2->num_rows > 0){
while ($obj2 = $stmt2->fetch_object()){
echo "<p>($obj2->Tot)</p>";
}
}
else
echo "<p>(0)</p>";
$stmt2->close();
}
}
else {
echo "<section class='error'><h1>There was a problem with the database.</h1></section>";
}
mysqli_free_result($stmt);
for ($i = $page - $x; $i < $page; $i++)
{
if ($i >= 1) {
$pagination .= "$i ";
}
}
$pagination .= " " . $i . " ";
for ($i = $page + 1; $i <= $page + $x; $i++)
{
if ($i <= $totalpages) {
$pagination .= "$i ";
}
}
/*for ($i = 1; $i <= $totalpages; $i++)
{
if ($i != $page){
$pagination .= "$i ";
}
else{
$pagination .= " " . $i . " ";
}
}*/
mysqli_close($link);
echo $pagination;
echo "</section>";
?>
The only thing I couldn't get was having a "next" or "previous" button. If anyone is up to the task of adding on those buttons, give it a shot. Other wise..... Enjoy..... :) This is my way of giving back to the stackoverflow community for helping me.

php pagination numbered page links

This is a pagination code used for the navigation, any ideas how to get this code to display simply a numbered list of the pages as links?
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
}
else {
$pageno = 1;
}
if(isset($_GET['niche']))
{
$query = "SELECT count(*) FROM studies WHERE niche = '{$_GET['niche']}'";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 4;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}' $limit";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
and...
if ($pageno == 1) {
echo "<div class='container'>FIRST PREV ";
} else {
echo "<div class='container'> <a href='{$_SERVER['PHP_SELF']}?pageno=1&niche={$_GET['niche']}'>FIRST</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage&niche={$_GET['niche']}'>PREV</a> ";
} // if
echo " ( Page $pageno of $lastpage ) ";
if ($pageno == $lastpage) {
echo " NEXT LAST</div><br />";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage&niche={$_GET['niche']}'>NEXT</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage&niche={$_GET['niche']}'>LAST</a></div><br /> ";
} // if
?>
Try this:
$totalpages = ceil($numrows / $rows_per_page);
if($totalpages >= 1){ $pagelinkcount = 1; } else { $pagelinkcount = 0; }
while($pagelinkcount <= $totalpages && $totalpages > 1) {
echo "{$pagelinkcount} ";
$pagelinkcount++;
}
On a side note, as Ian Elliot pointed out in the comments for your question, using $_GET in an SQL query leaves your database VERY vulnerable, and is thus considered an extremely insecure coding practice. You should escape and parse the $_GET data that you need diligently before passing it to the DB.
Here's a function I've been using for pagination for a while. It returns nothing if there's only one page, returns up to 15 pages with numbers, then adds a dropdown that lets you skip to any 10th page when there are more than 15 pages. It relies on some prev/next images, but you can easily take that out.
function paginate( $items_per_page, $number_of_results ) {
if( isset( $_REQUEST['page'] ) ) {
$page = $_REQUEST['page'];
} else {
$page = 1;
}
$url = htmlentities( preg_replace( '/(\?|&)page=[\d]+/', '', $_SERVER['REQUEST_URI'] ).'&' );
$html = '';
$numbers_html = '';
$navigation_html = '';
if( $number_of_results > $items_per_page ) {
$html .= '<div class="pagination">';
if( $page == 1 or $page == '1' ) {
$numbers_html .= '<img src="images/prev.png" alt="← prev" class="inactive" /> - ';
} else {
$numbers_html .= '<img src="images/prev.png" alt="← prev" /> - ';
}
$count = 0;
$total_pages = ceil( $number_of_results / $items_per_page )-1;
while( $count <= $total_pages ) {
$count++;
if( $total_pages > 12 and floor($count / 10) != floor($page / 10) ) {
while( $count < $total_pages and floor($count / 10) != floor($page / 10) ) {
if( $count == 1 ) {
$endpage = 9;
} elseif( $count + 9 < $total_pages ) {
$endpage = $count + 9;
} else {
$endpage = $total_pages + 1;
}
$ten_group = floor( $count / 10 );
if( $ten_group == 0 ) {
$navigation_html .= '<option value="'.$url.'page='.$count.'">page 1</option>';
} else {
$navigation_html .= '<option value="'.$url.'page='.$count.'">page '.($ten_group*10).'</option>';
}
$count += 10;
}
$count -= 2;
} else {
if( $page == $count ) {
$numbers_html .= '<span class="current">'.$count.'</span>';
if( $count == 1 ) {
$endpage = 9;
} elseif( $count + 9 < $total_pages ) {
$endpage = $count + 9;
} else {
$endpage = $total_pages + 1;
}
if( $total_pages > 15 ) {
$ten_group = floor( $count / 10 );
if( $ten_group == 0 ) {
$navigation_html .= '<option value="'.$url.'page='.$count.'" selected="selected">page 1</option>';
} else {
$navigation_html .= '<option value="'.$url.'page='.$count.'" selected="selected">page '.($ten_group*10).'</option>';
}
}
} else {
$numbers_html .= ''.$count.'';
}
if( ( $total_pages > 12 and $count % 10 == 9 ) or $count == $total_pages+1 ) {
} else {
$numbers_html .= ' - ';
}
}
}
if( $page != $count ) {
$numbers_html .= ' - <img src="images/next.png" alt="next →" />';
} else {
$numbers_html .= ' - <img src="images/next.png" alt="next →" class="inactive"/>';
}
$count++;
$html .= '<div class="pagination_numbers">'.$numbers_html.'</div>';
if( $navigation_html ) {
$html .= '<div class="pagination_navigation">skip to: <select onchange="window.location=this.value">'.$navigation_html.'</select> of '.($total_pages+1).'</div>';
}
$html .= '</div>';
}
return $html;
}
If you have many pages to display, you might want to consider "logarithmic" page naviagtion, as I describe in my answer here:
How to do page navigation for many, many pages? Logarithmic page navigation
(Sample PHP code only handles the pagination display - not the DB query).

Categories