My table is posting and in that table, it shows all the posting people put in.
I am trying to make page navigation links at the bottom of the posts.
the function generateenter code here_page_links does all the work.
The code seem to be only showing the "<-" and "->" and not the link numbers. I think the function is only reading the $_GET['posting'] ==1.
(this code is from the Oreilly PHP/MySQL book. I am using it as practice)
function generate_page_links($cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "previous" link
if ($cur_page > 1) { //cur_page is just a number that is gotten from the url.
$page_links .= '<-- ';
}
else {
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
for ($i = 1; $i <= $num_pages; $i++) {
if ($cur_page == $i) {
$page_links .= ' ' . $i;
}
else {
$page_links .= ' ' . $i . '';
}
}
// If this page is not the last page, generate the "next" link
if ($cur_page < $num_pages) {
$page_links .= ' ->';
}
if ($cur_page == $num_pages){ //the last page
$page_links .= ' ->';
}
return $page_links; //need to return this variable in the function
}
// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 3; // number of results per page
$skip = (($cur_page - 1) * $results_per_page);
$query = "SELECT * FROM posting ORDER BY date_added DESC";
$data = mysqli_query($dbc, $query);
$total = mysqli_num_rows($data);
$num_pages = ceil($total / $results_per_page);
//Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
$result = mysqli_query($dbc, $query);
echo '<table>';
echo '<tr><td><b>Title</b></td><td><b>Date Posted</b></td></tr>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr><td><a href="ad.php?
posting_id='.$row['posting_id'].'
">'.$row['title'].'</a></td>';
echo '<td>'.$row['date_added'].'</td>';
//echo '<td>'.$row['name'].'</td></tr>';
}
echo '</table>';
// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
}
Well you have some problems here to start with:
You call the function with 4 variables
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
But the function only accepts two
function generate_page_links($cur_page, $num_pages)
If that's the code you're using, then it's probably going to crash because those variables are undefined.
Try deleting "$user_search, $sort," and see if that fixes it?
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 got the pagination controls and my search results shows 5 results fine. but when I click the second page, all of the search results go away. even though for what I searched, there is more than 5 results in the database. if you would please see the update code in just a second. here is my email bud just in case: raminrahim [at] hotmail [dot] com Please. thanks.
<?php
$paginationCTRLS = '';
$textline1 = '';
$textline2 = '';
$list = '';
if (isset($_GET['search_item'])) {
$search_item = $_GET['search_item'];
if (!empty($search_item)) {
if (strlen($search_item)>=3) {
// This query is just to get total count of rows
$query= "SELECT COUNT(item_id) FROM items"; // $sql
$query_run = mysqli_query($mysqli, $query); // $query
$query_row = mysqli_fetch_row($query_run); // $row
// $rows: here we have the total row count
$rows = $query_row[0]; // pgRows = row[]
// This is the number of results we want displayed per page
$page_rows = 5;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure last cannot be less than 1.
if ($last < 1)
{
$last = 1;
}
// Establish the $pagenum variables
$pagenum = 1;
// Get pagenum from URL vars if it present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$query = "SELECT `item_id`, `featured_Items` FROM `items` WHERE
`featured_Items` LIKE
'%".mysql_real_escape_string($search_item)."%' $limit";
$query_run = mysqli_query($mysqli, $query);
$query_num_rows = mysqli_num_rows($query_run);
if ($query_num_rows>=1)
{
echo $query_num_rows. ' results found:<br>' . '<br>';
while ($query_row = mysqli_fetch_assoc($query_run))
{
echo $query_row['featured_Items'].'<br>' . '<hr>';
}
}
else
{
echo 'No result found' . '<hr>';
}
} else {
echo 'Not enough keywords to predict your search' . '<hr>';
}
}
$textline1 = "Result:" . '(<b>$rows</br>)';
$textline2 = "Page <b>" . '$pagenum' . "</b> of <b>" . '$last' . "</b>";
if ($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCTRLS .= 'Back ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i>0){
$paginationCTRLS .= ''.$i.' ';
}
}
}
$paginationCTRLS .= ''.$pagenum.' ';
for ($i = $pagenum+1; $i <= $last; $i++) {
$paginationCTRLS .= ''.$i.' ';
if($i >= $pagenum+4) {
break;
}
}
if ($pagenum != $last) {
$next = $pagenum +1;
$paginationCTRLS .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($query_run, MYSQLI_ASSOC)) {
$id = $row["item_id"];
$availablesITEMS = $row["featured_Items"];
$list .= '<p>'.$availablesITEMS.'<br>.</p>';
}
}
echo $list . '<br/>';
echo $paginationCTRLS . '<br/>';
?>
You need to set up your query to be able to accept an start point.
Like this:
LIMIT 0, 10
Where the first number corresponds to the starting row your results are going to be obtained from, and the second number equals the amount of results you're going to get from that point on.
So in the sense of your code you'd have to set it up as:
$query = "SELECT `item_id`, `featured_Items` FROM `items` WHERE
`featured_Items` LIKE
'%".mysql_real_escape_string($search_item)."%'
LIMIT ".($pagenum-1)*5.",5";
Let me know if that clears up your doubt.
Edit:
As for enabling pagination through your means, simply change the method in your form to be a GET statement.
<form action="your_page.php" method="get">
Then from your code you can use the
$_GET['search_item']
method instead of POST. This in turn enables you to use those variables on your anchor tags for your pagination.
$paginationCTRLS .= ''.$i.' ';`
Edit2:
You have this piece of code:
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i>0){
$paginationCTRLS .= ''.$i.' ';
}
}
This will always at any point output the same number of pages, which is 5.
Now what you need is something that outputs only the pagination that you really need. So for example setting up this variable:
$pages = ceil($row/$page_rows);
Gives you your total amount of pages, then you can iterate to it:
for($i = 1; $i <= $pages; $i++){
if($i>0){
$paginationCTRLS .= ''.$i.' ';
}
}
I was able to create a working pagination system for my application. But the problem I am having is when a user does a search, it can/will display over 100 pages in the pagination.
I am trying to figure out how to show only like 5 on each side of the current page. I would like to create a FIRST page button, and a LAST page button, but I'll deal with that later.
So here is the first part of code that counts the records in the database table:
<?php
function countRecords()
{
// The application takes a lot of user input, which then builds a query here.
// The user input goes into a session variable called $_SESSION['where']
// I'll start with the actual query code
$sql = "SELECT COUNT(DISTINCT CONTAINER_NUMBER) AS TOTAL
FROM 'contTable'" . " WHERE (" . $_SESSION['where'] . ");";
$sqlres = #mysql_query($sql) or die();
$row = mysql_fetch_row($sqlres);
$return $row[0];
}
So code above gets the count from the table depending on the search criteria.
Here is the next piece of code that prints the grid. I'll keep it as short as possible:
function displayrecords()
{
$rec_limit = 100;
$targetpage = "containers.php";
if(isset($_GET['page']))
{
$page = $_GET['page'];
$offset = $rec_limit * ($page - 1);
}
else
{
$page = 1;
$offset = $rec_limit * ($page - 1);
}
$left_rec = countRecords() - ($page * $rec_limit);
$select = "";
$_SESSION['where'] = "";
// user input variables are here that build a variable called $_SESSION['where']
// I'll skip the code down to the query
if ($_SESSION['where'] != "") $select = "SELECT * FROM 'contTable'" . " WHERE
(" . $_SESSION['where'] . ") GROUP BY container, bol LIMIT " . $offset . ",
" . $rec_limit . ";";
}
Please excuse any typos or missing brackets and whatnot. Just know the above code works.
Now here is the code for the rest of the pagination:
$total_records = countRecords();
$total_pages = ceil($total_records / $rec_limit);
$adjacents = 5; // I just added this variable. I don't know what to do with it
$previousPage = $page - 1;
$nextPage = $page + 1;
$querystring = "";
foreach ($_GET as $key => $value)
{
if ($key != "page") $querystring .= "$key=$value&";
}
echo '<ul style="border: 0px solid red; margin: 3px;" class="pager">';
if ($left_rec < $rec_limit)
{
$last = $page - 2;
echo #"<li><a href=\"$targetpage?page=$previousPage&$querystring\">
Previous</a></li>";
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
}
else if ($page == 0)
{
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
echo #"<li>Next</li>";
}
else if ($page > 0)
{
$last = $page - 2;
echo #"<li><a href=\"$targetpage?page=$previousPage&$querystring\">
Previous</a></li> ";
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
echo #"<li>Next</li>";
}
echo '</ul>';
}
So, with all of the code above, I can display a grid, and display the pages at the bottom of the application. But I don't want to show all 100 pages, only 5 on each side of the current page. I know I need to utilize the variable called $adjacents and plug it in to the paging portion of the code. But I'm not exactly sure how to do it.
I hope I am being clear on my request.
Please help.
Instead of looping through all of the pages:
for($i = 1; $i <= $total_pages; $i++)
Try doing something like this:
$start = ($page < $adjacents ? 1 : $page - $adjacents);
$end = ($page > $total_pages - $adjacents ? $total_pages : $page + $adjacents);
for($i= $start; $i <= $end; $i++)
//Here you can loop through the numbers within adjacents of the current page
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