I have a pagination system, that fetches all of the results from a database & then loads them into a pagination.
Let's say I set the limit to 5 results per page, it will generate more pages, and order the results by date & time.
But I have a problem, my system always missing the most new result (by date/time) in the database, I have no idea why..
This is the code:
// how many rows to show per page
$rowsPerPage = 10;
// by default we show first page
$page_num = 1;
// if $_GET['page'] defined, use it as page number, $_GET gets the page number out of the url
//set by the $page_pagination below
if(isset($_GET['page'])){$page_num = $_GET['page'];}
//the point to start for the limit query
$offset = $page_num;
// Zero is an incorrect page, so switch the zero with 1, mainly because it will cause an error with the SQL
if($page_num == 0) {$page_num = 1;}
// counting the offset
$sql = "SELECT * FROM comments ORDER BY date, time desc LIMIT $offset, $rowsPerPage";
$res = $pdo->query($sql);
// how many rows we have in database
$sql2 = "SELECT COUNT(comment_id) AS numrows FROM comments";
$res2 = $pdo->query($sql2);
$row2 = $res2->fetch();
$numrows = $row2['numrows'];
// print the random numbers
while($row = $res->fetch())
{
//Echo out your table contents here.
echo $row[1].'<BR>';
echo $row[2].'<BR>';
echo '<BR>';
}
// how many pages we have when using paging?
$numofpages = ceil($numrows/$rowsPerPage);
// print the link to access each page
$self = "events.php?";
$page_pagination = '';
if ($numofpages > '1' ) {
$range = 10; //set this to what ever range you want to show in the pagination link
$range_min = ($range % 2 == 0) ? ($range / 2) - 1 : ($range - 1) / 2;
$range_max = ($range % 2 == 0) ? $range_min + 1 : $range_min;
$page_min = $page_num- $range_min;
$page_max = $page_num+ $range_max;
$page_min = ($page_min < 1) ? 1 : $page_min;
$page_max = ($page_max < ($page_min + $range - 1)) ? $page_min + $range - 1 : $page_max;
if ($page_max > $numofpages) {
$page_min = ($page_min > 1) ? $numofpages - $range + 1 : 1;
$page_max = $numofpages;
}
$page_min = ($page_min < 1) ? 1 : $page_min;
if ( ($page_num > ($range - $range_min)) && ($numofpages > $range) ) {
$page_pagination .= '<a class="num" title="First" href="'.$self.'page=1"><</a> ';
}
if ($page_num != 1) {
$page_pagination .= '<a class="num" href="'.$self.'page='.($page_num-1). '">Previous</a> ';
}
for ($i = $page_min;$i <= $page_max;$i++) {
if ($i == $page_num)
$page_pagination .= '<span class="num"><strong>' . $i . '</strong></span> ';
else
$page_pagination.= '<a class="num" href="'.$self.'page='.$i. '">'.$i.'</a> ';
}
if ($page_num < $numofpages) {
$page_pagination.= ' <a class="num" href="'.$self.'page='.($page_num + 1) . '">Next</a>';
}
if (($page_num< ($numofpages - $range_max)) && ($numofpages > $range)) {
$page_pagination .= ' <a class="num" title="Last" href="'.$self.'page='.$numofpages. '">></a> ';
}
}
echo $page_pagination.'<BR><BR>';
echo 'Number of results - '.$numrows ;
echo ' and Number of pages - '.$numofpages.'<BR><BR>';
$res2->closeCursor();
Question:
What have I done wrong? I cant' really see anything wrong, but I always get this error:
Notice: Undefined variable: page_pagination
Line:
echo $page_pagination.'<BR><BR>';
It always happens on a different line, depends on the results amount, but to fix that I need to declare page_pagination = ''; before the whole thing.
How can I fix this and what is causing this problem?
Thanks.
Your $offset is being set to 1. The newest one is always missing because it's going form 1-10 rather than 0-9. Index starts at 0. The following should work.
$offset = ($rowsPerPage * $page_num) - $rowsPerPage;
Related
i create a php news system, but i have a problem:
<?php
include('config.php');
if( isset( $_GET["page"]) ) $PAGE=$_GET["page"]; else $PAGE=1;
$query1=mysql_query("select id, name, email , age from addd LIMIT ". (($PAGE * 5) - 5) .",5");
echo "<table><tr><td>Testo</td><td>Nome</td><td>Anni</td></tr>";
function truncate_string($str, $length) {
if (!(strlen($query2['name']) <= $length)) {
$query2['name'] = substr($query2['name'], 0, strpos($query2['name'], ' ', $length)) . '...';
}
return $query2['name'];
}
while($query2=mysql_fetch_array($query1))
{
$number= $query2['name'];
echo "<tr><td>".substr($query2['name'], 0, 500)."...</td>";
echo "<td>".$query2['email']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td>".str_word_count($number)."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Mod</a></td>";
echo "<td><a href='delete.php?id=".$query2['id']."' onclick=\"return confirm('Sei sicuro di volerlo eliminare?');\");'>Canc</a></td><tr>";
echo "<td><a href='singletwo.php?id=".$query2['id']."');'>vedi</a></td<tr>";
}
?>
The pages follow this numbering: ?page=1, ?page=2 ecc.
Each page contains 5 news.
How do I create an automatic pagination system?
With Prev-Next, automatically detect possible next or previous pages?
I don't know how to do it.
Start by having the max length and total number of rows in variables:
<?php
include('config.php');
$max = 5;
$total = mysql_query("select count(*) from addd");
$PAGE = isset($_GET["page"]) ? $_GET["page"] : 1;
$query1 = mysql_query("select id, name, email , age from addd LIMIT " . (($PAGE * $max) - $max) . "," . $max);
That way, you can calculate how many pages you'll need.
The following code will give you a page list (Page 1, Page 2, Page 3 etc.):
for($i = 0; $i < ceil($total / $max); $i ++)
{
$p = $i + 1;
echo 'Page ' . $p . '';
}
If you'd rather have Previous and Next links, try this:
if($PAGE > 1)
echo '<a href="?page=' . ($PAGE - 1) . '>Previous</a>';
if(ceil($total / $max) > $PAGE)
echo '<a href="?page=' . ($PAGE + 1) . '>Next</a>';
What you could do is:
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = $currentPage*5;
$offset = $offset-5;
Now that you have these numbers, you can use them in your query:
$stmt = "SELECT
...
FROM news
LIMIT ".$offset.", ".$limit.";
This way you'll get the records you want. As far as the next and previous buttons go:
if ($currentPage > 1) {
// Show previous button
}
For the next button you'll need to do another query:
$stmt = "SELECT COUNT(*) as total FROM news";
$result = $pdo->fetch();
$totalRows = $result['total'];
if ($currentPage < round($totalRows/5)) {
// Show next button
}
I am currently working on a website which is basically search based. End users can search the members that are currently registered on the website. The registered users can avail 3 membership packages Golden, Silver and Basic. I have a pagination in place and when I try to sort the result based on the package, I get duplication of results on different pages. For example, if I get a user on page 3, he may also appear on, say, page 6. I don't know what i am doing wrong. Any help will be highly appreciated. I am pasting below my MySQL query that is fetching the result from the database.
SELECT * FROM users
LEFT JOIN prof_info
ON users.id = prof_info.user_id
WHERE (prof_info.work_country = 'Indonesia'
OR (prof_info.work_country ='' AND users.country = 'Indonesia'))
AND users.firstname !=''
ORDER BY users.membership DESC
LIMIT 0, 10
Membership packages have following database entry:
Golden=2, Silver=1, Basic=0. I want to be able to show Golden members in search result, than silver and afterwords basic members.
Code that creates pagination is
<?php
if (isset($_GET["page"])) { $current_page = $_GET["page"]; } else { $current_page=1; };
$limit = 1; // number of results per page
$start_from = ($current_page-1) * $limit;
if(isset($total_results)){
$nav = '';
$skip_links1 = 1;
$skip_links2 = 1;
for($page = 1; $page <= $total_pages; $page++)
{
if ($page == $current_page)
{
$nav .= " $page "; // no need to create a link to current page
}
else
{
if(($page > 2) && ($page < $total_pages-2) && ($page > $current_page + 2)){//number of pages exceeding 5
if($skip_links1 == 1)
$nav .= " ... ";
$skip_links1 =0;
}elseif($page >2 && $page < $current_page -2 ){
if($skip_links2 == 1)
$nav .= " ... ";
$skip_links2=0;
}else{
$nav .= "<a href='doctors.php?page=".$page."&country=".$_GET['country']."&city=".$_GET['city']."&speciality=".$_GET['speciality']."&name=".$_GET['name']."'>".$page."</a> ";
}
}
}
if ($current_page > 1)
{
$page = $current_page - 1;
$prev = " <a href='doctors.php?page=".$page."&country=".$_GET['country']."&city=".$_GET['city']."&speciality=".$_GET['speciality']."&name=".$_GET['name']."'><</a> ";
$first = " <a href='doctors.php?page=1&country=".$_GET['country']."&city=".$_GET['city']."&speciality=".$_GET['speciality']."&name=".$_GET['name']."'><<</a> ";
}
else
{
$prev = ' '; // we're on page one, don't print previous link
$first = ' '; // nor the first page link
}
if ($current_page < $total_pages)
{
$page = $current_page + 1;
$next = " <a href='doctors.php?page=".$page."&country=".$_GET['country']."&city=".$_GET['city']."&speciality=".$_GET['speciality']."&name=".$_GET['name']."'>></a> ";
$last = " <a href='doctors.php?page=".$total_pages."&country=".$_GET['country']."&city=".$_GET['city']."&speciality=".$_GET['speciality']."&name=".$_GET['name']."'>>></a> ";
}
else
{
$next = ' '; // we're on the last page, don't print next link
$last = ' '; // nor the last page link
} ?>
<div id="tableNav">
<?php
echo "<center>".$first . $prev . $nav . $next . $last."</center>";
?>
</div>
<?php
}//end of if(isset($total_results))
?>
First of all swap LEFT JOIN to INNER JOIN because you have on clause.
Secondly, it seems like you have duplicates in your table. You can get only 1 membership type per user, for example highest one by using this query
SELECT
*,MAX(users.membership)
FROM
users
INNER JOIN
prof_info ON users.id = prof_info.user_id
WHERE
(prof_info.work_country = 'Indonesia'
OR (prof_info.work_country = ''
AND users.country = 'Indonesia'))
AND users.firstname != ''
GROUP by users.id
ORDER BY users.membership DESC
LIMIT 0 , 10
I am using this coed in PHP to show next and previous buttons for records in a mysql database:
$sql="SELECT * from customer";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$MaxRowsPerPage = 25;
$total_records = mysql_num_rows($rs);
$total_pages = ceil($total_records / $MaxRowsPerPage);
if(isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
}
$start_from = ($page-1) * $MaxRowsPerPage;
$sql.=" LIMIT $start_from, $MaxRowsPerPage";
I am echoing $total_records to show the total amount, how can i show the number from and to on the current page. for example, on page 1 it will be showing records 1 to 25 (because max rows per page is 25) and then page 2 will be showing records 26 to 50 and so on...
There a are many ways of doing this, but here's a simple pagination example I made. It will also show 1-25, 26-50 etc. It's heavily commented so it should be easy to understand.
<?php
// Connect to database
include 'includes/db_connect.php';
// Find total number of rows in table
$result = mysql_query("SELECT COUNT(*) FROM example_table");
$row = mysql_fetch_array($result);
$total_rows = $row[0];
// Set rows per page
$rows_per_page = 25;
// Calculate total number of pages
$total_pages = ceil($total_rows / $rows_per_page);
// Get current page
$current_page = (isset($_GET['p']) && $_GET['p'] > 0) ? (int) $_GET['p'] : 1;
// If current page is greater than last page, set it to last.
if ($current_page > $total_pages)
$current_page = $total_pages;
// Set starting post
$offset = ($current_page - 1) * $rows_per_page;
// Get rows from database
$result = mysql_query("SELECT * FROM example_table LIMIT $offset, $rows_per_page");
// Print rows
echo '<hr>';
while($row = mysql_fetch_array($result))
{
echo $row['id'].'<br />';
echo $row['text'];
echo '<hr>';
}
// Build navigation
// Range of pages on each side of current page in navigation
$range = 4;
// Create navigation link for previous and first page.
if ($current_page > 1)
{
$back = $current_page - 1;
echo ' PREV ';
if ($current_page > ($range + 1))
echo ' 1... ';
}
else
echo ' PREV ';
// Create page links, based on chosen range.
for ($i = $current_page - $range; $i < ($current_page + $range) + 1; $i++)
{
if ($i > 0 && $i <= $total_pages)
if ($i == $current_page)
echo ' [<strong>'.$i.'</strong>] ';
else
echo ' '.$i.' ';
}
// Create navigation link for next and last page.
if ($current_page != $total_pages)
{
$next = $current_page + 1;
if (($current_page + $range) < $total_pages)
echo ' ...'.$total_pages.' ';
echo ' NEXT ';
}
else
echo ' NEXT ';
?>
Currently I have a functioning pagination script, although I'm missing on feature. At the moment it's possible for hundreds of pages to be showing in the $pages list, because there's no filter on to show between, for example, [1] [...] 5, 6, 7 [..] [45]. Here's my code:
/** Pagination **/
$limit = 7;
$query = "SELECT COUNT(*) FROM users";
$result = $db->prepare($query);
$result->execute();
$pages_query = $result->fetchColumn(0);
$count = number_format($pages_query);
$pages = ceil($pages_query / $limit);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;
ob_start();
echo("<span class='alignright'>");
if ($pages >= 1 && $page <= $pages){
if($page > 1){
$next = ($page - 1);
$link = "?page=$next";
echo("<a class='paginate' href='$link'><i class='icon-caret-left'></i></a>");
}
for ($x=1; $x<=$pages; $x++){
echo ($x == $page) ? "<strong style='font-weight: bold!important;'><a class='paginate' href='?page=$x'>$x</a></strong>" : "<a class='paginate' href='?page=$x'>$x</a>";
}
if($page < $pages){
$next = ($page + 1);
$link = "?page=$next";
echo("<a class='paginate' href='$link'><i class='icon-caret-right'></i></a>");
}
echo("</span>");
if($count > 0){
echo("<span class='smalltext'>Page <strong class='half'>$page</strong> of $pages:</span>");
} else {
echo("<span class='smalltext'>There are <span class='half'>$count</span> results to display.</span>");
}
$pagintion = ob_get_clean();
(It's been stripped from other junk that was in it but that's the general frame.) Basically I'm trying to figure out how to limit it to have "between pages" down the bottom as specified in the top part of the question. Something like:
[<] [1] ... [4] [5] [6] ... [45] [>]
If that makes sense.
you can try LIMIT with in your query itself
SELECT * FROM TABLE_NAME LIMIT STARTING_RESULT_NUMBER, RESULTS_PER_PAGE
RESULTS_PER_PAGE is no.of items per page you want to display
STARTING_RESULT_NUMBER =(CURRENT_PAGE_NUMBER*RESULTS_PER_PAGE)
In order to change the list of pages to something like [<] [1] ... [4] [5] [6] ... [45] [>] rather than showing all pages numbers, you can replace your for loop by something like :
echo "<a class='paginate' href='?page=1'>1</a>";
if($page > 3) {echo "...";}
if($page > 2) {echo "<a class='paginate' href='?page=" . $x-1 . "'>" . $x-1 "</a>";}
if($page != 1 && $page != pages) {echo "<a class='paginate' href='?page=" . $x . "'>" . $x "</a>";}
if($page < $pages-1) {echo "<a class='paginate' href='?page=" . $x+1 . "'>" . $x+1 "</a>";}
if($page < $pages-2) {echo "...";}
if($pages >1) {echo "<a class='paginate' href='?page=1'>1</a>";}
Il will show the first page, the last pages, the current pages and the ones just before and just after.
My personal meaning with pagination is that it must be readable and simple to change later on.
I typed the following code based on you're example:
$totalPages = 145; //the total amount of pages
$selectedPage = 40; //the selected page
$pages = array(); //the array which is gonna hold the pages we need to display
$offset = 3; //the number of pages to select around the selected page
$closePages = range($selectedPage - $offset, $selectedPage + $offset); //select the pages that are in $offset of the selected page
array_filter($closePages, function($x) { //filter the pages below 1 and above $totalPages
return ($x <= $totalPages && $x >= 1 ? true : false );
});
array_push($pages, 1); //add the first page
array_push($pages, '...'); //add some dots
$pages = array_merge($pages, $closePages);
array_push($pages, '...'); //and again add some dots
array_push($pages, $totalPages); //add the last page
Then you use a foreach loop to display the pages:
foreach($pages as $page) {
if (is_numeric($page)) {
if ($page != $selectedPage) $content .= ' ' . $page . ' ';
else $content .= ' <strong>' . $page . '</strong> ';
} else
$content .= '[...]';
}
Some explanation after you're comment on this answer:
The $totalPages variable must be the total amount of pages on the page (from you're example) and the $selectedPage is the page that is selected at this moment.
$totalPages = ceil($pages_query / $limit);
$selectedPage = isset($_GET['page']) ? $_GET['page'] : 1;
I have two tiny little problems;
1 . I want to add a previous / next button into this code
2 . I want it to only show like max 10 links between previous and next. So if i have 50 numbers/links it will only show 10 of them and not 50 links on the page.
I have searched on the clo
The code works, only need that two options in it.
Can someone help me out? Thank you !
<?php
include 'includes/connection.php';
$per_page = 8;
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `products`");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysql_query("SELECT `name` FROM `products` LIMIT $start, $per_page");
while ($query_row = mysql_fetch_assoc($query)) {
echo '<p>', $query_row['name'] ,'</p>';
}
if ($pages >= 1 && $page <= $pages) {
for ($x=1; $x<=$pages; $x++) {
//echo $x, ' ';
echo ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
}
}else{
header("location:index.php?page=1");
}
?>
First of all, you should, just for good practice, put an "exit;" after the header() call at the end. It doesn't make a difference in this particular script, but keep in mind that any code following a header("Location: ...") call WILL be executed before redirection.
Now to your question, try this (UPDATE: This code has been tested and works.)
<?php
include 'includes/connection.php';
$per_page = 8;
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `products`");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysql_query("SELECT `name` FROM `products` LIMIT $start, $per_page");
while ($query_row = mysql_fetch_assoc($query))
{
echo '<p>' . $query_row['name'] . '</p>';
}
// If the requested page is less than 1 or more than the total number of pages
// redirect to the first page
if($pages < 1 || $page > $pages)
{
header('Location: ?page=1');
// end execution of the rest of this script
// it will restart execution after redirection
exit;
}
// If more than one page, show pagination links
if($pages > 1)
{
$html = array();
$html[] = '<strong>';
// if you're on a page greater than 1, show a previous link
$html[] = (($page > 1) ? 'Previous ' : '');
// First page link
$pageFirst = '1';
$html[] = (($page == 1) ? "</strong>{$pageFirst}<strong>" : $pageFirst);
if ($pages > 6)
{
$start_cnt = min(max(1, $page - (6 - 1)), $pages - 6);
$end_cnt = max(min($pages, $page + 4), 8);
$html[] = ($start_cnt > 1) ? '...' : ' ';
for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
{
$html[] = ($i == $page) ? '</strong>' . $i . '<strong>' : '' . $i . '';
if ($i < $end_cnt - 1)
{
$html[] = ' ';
}
}
$html []= ($end_cnt < $pages) ? '...' : ' ';
}
else
{
$html[] = ' ';
for ($i = 2; $i < $pages; $i++)
{
$html[] = ($i == $page) ? '</strong>' . $i . '<strong>' : '' . $i . '';
if ($i < $pages)
{
$html[] = ' ';
}
}
}
// last page link
$pageLast = '' . $pages . '';
$html[] = (($page == $pages) ? "</strong>{$pageLast}<strong>" : $pageLast);
// Show next page link if you're on a page less than the total number of pages
$html[] = ($page < $pages) ? ' Next' : '';
// If you're not on the last page, show a next link
$html[] = '</strong>';
}
else
{
// show page number 1, no link.
$html[] = '<strong>1</strong>';
}
echo implode('', $html);
Also note that the final ?> is not required in PHP files that do not have HTML code following the PHP code, so I left it off.
Buddy refer this URL
http://www.codediesel.com/php/simple-pagination-in-php/
OR
http://www.phpfreaks.com/tutorial/basic-pagination
Surely will help you.
Thanks