I have a small problem with my PHP pagination, I have 6 records and I display 2 at a time, when I click on next and it displays from 2 to 4 records, that works fine, But to display from 4 to 6 records, that does not work. I am not sure what im doing wrong. Anyone have any ideas ? the problem is to do with the calculation for the Next records to be displayed
<?php
$per_page = 2;
$start = $_GET['start'];
$query = mysql_query("SELECT * FROM Directory");
$record_count = mysql_num_rows($query);
$record_count = round($record_count / $per_page);
if(!$start) {
$start = 0;
}
$query = mysql_query("SELECT * FROM Directory LIMIT $start,$per_page") or die(mysql_error());
$row = mysql_num_rows($query);
// Output Records here
// Setup next and previous button variables
$prev = $start - $per_page;
$next = $start + $per_page;
echo '<p> <h4>';
if($prev < 0) {
echo 'Previous';
} else {
echo '<a href="directory.php?start='.$prev.'>Previous</a>';
}
echo ' ' . $start . ' of ' . $record_count;
if($next < $record_count) {
echo ' <a href="directory.php?start='.$next.'>Next</a>';
} else {
echo ' Next';
}
echo '</h4> </p>';
?>
It looks like it's a formatting issue. When I look at your source for the URL http://gebsbo.limewebs.com/directory/directory.php?start=1 I see:
<br /><p> <h4>Previous 1 of 4 <a href="directory.php?start=3>Next</a></h4> </p> </body>
It looks like you're missing a quote on the href attribute.
In your code, you want:
echo 'Previous';
and
echo ' Next';
use this code for calculating :
$num = 10; // number of items on page
$p = $_GET['page']; // the var that comes from url (for ex: htttp://..../xxx.php?page=3)
$r = mysql_query(" select * from your_table ");
$posts=mysql_num_rows($r); // total posts
$total=(($posts-1)/$num)+1; // toatal pages
$total=intval($total);
$p=intval($p);
if(empty($p) or $p<0 or !isset($p)) $p=1;
if($p>$total) $p=$total;
$start=$p*$num-$num;
// here print the html for pagination (for ex: htttp://...../xxx.php?page=1 .. 2 ...3 .... and so on ...) you can make a for() here
$r = mysql_query(" select * from your_table limit ".$start.", ".$num);
while (....) {
.....
}
Related
I have a website that I'm building on my localhost using the MVC design pattern. I have button on click that will display all the genres in TheMovieDatabase which I got using the TheMovieDatabaseAPI. On click of a genre I get data for Page 1 with 20 results. But, I couldn't figure out how to request the results for page 2. These requests are made using PHP.
I am assuming you are taking about pagination using, I am also assuming you are using mySQL as database, I am not sure which framework you are using,
Here is a function i use, you can build around this
function get_movie($page = 1){
global $database_connection;
$start = 0; //Don't modify this
$limit = 10; //set this to 20 to display 20 movies per page
$start = ($page - 1)* $limit;
//get the movie from the table
$sql = "SELECT genre FROM movie_table LIMIT $start, $limit";
$result = mysqli_query($database_connection, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div>$row['genre']</div>";
}
$movie_rows = mysqli_num_rows (mysqli_query($database_connection ,"SELECT * FROM movie_table"));
$total = ceil($testimony_rows / $limit);
if (isset($page)){
echo "<div>";
echo "<ul class='pager'>";
if($page > 1) {
echo "<a href='?page=".($page - 1)."' style='float: left;' class=' w3-sand w3-btn w3-margin w3-round'>Previous</a>";
}
for($i = 1; $i <= $total; $i++) {
if($i == $page) { echo "<li class='active current'>".$i."</li>"; }
else { echo "<li><a href='?page=".$i."'>".$i."</a></li>"; }
}
if($page != $total) {
echo "<a href='?page=".($page + 1)."' class='w3-btn w3-margin w3-sand w3-round'>Next</a>";
}
echo "</ul></div>";
}
}
you can use limit and offset to get the result for page 2.
Example :- if you are using query builder to get the results
$limit = 20;
$offset = 21;
$queryBuilder->select('d')
->from(<table name>, 'd')
->setMaxResults($limit)
->setFirstResult($offset)
->setParameter('limit', $limit)
->setParameter('offset', $offset);
If you are using raw query :
SELECT * FROM table LIMIT 20 OFFSET 21
Else you can use paginator too
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);
$totalItems = count($paginator);
$pagesCount = ceil($totalItems / $pageSize);
// now get one page's items:
$paginator
->getQuery()
->setFirstResult($pageSize * ($currentPage-1)) // set the offset
->setMaxResults($pageSize); // set the limit
foreach ($paginator as $pageItem) {
echo "<li>" . $pageItem->getName() . "</li>";
}
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 ';
?>
I have the following mysql query and I have added pagination from here:
http://www.tonymarston.net/php-mysql/pagination.html
$DBQuery3 = mysqli_query($dblink, "SELECT * FROM images WHERE project_id = '$FormProjectID'");
if (mysqli_num_rows($DBQuery3) < 1) {
$ProjectContent = '
<p>This project is empty. Upload some files to get started.</p>
';
} else {
//if no page number is set, start at page 1
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
//This code will count how many rows will satisfy the current query.
$DBQuery3b = mysqli_query($dblink, "SELECT count(*) FROM images WHERE project_id = '$FormProjectID'");
$query_data = mysqli_fetch_row($dblink, $DBQuery3b);
$numrows = $query_data[0];
//This code uses the values in $rows_per_page and $numrows in order to identify the number of the last page.
$rows_per_page = 2;
$lastpage = ceil($numrows/$rows_per_page);
//This code checks that the value of $pageno is an integer between 1 and $lastpage.
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
//This code will construct the LIMIT clause for the sql SELECT statement.
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$DBQuery3c = "SELECT * FROM images WHERE project_id = $FormProjectID $limit";
$DBQuery3d = mysqli_query($dblink, $DBQuery3c);
//set this variable to empty and so we can latwe loop and keep adding images to it
$ProjectContent ='';
while($row = mysqli_fetch_array($DBQuery3d)) {
$DBImageID = $row['image_id'];
$DBProjectID = $row['project_id'];
$DBImageName = $row['image_name'];
$DBImageDescription = $row['image_description'];
$DBDateCreated = $row['date_created'];
$DBLinkToFile = $row['link_to_file'];
$DBLinkToThumb = $row['link_to_thumbnail'];
$DBGivenName = $row['given_name'];
//if the image was given a name by the user, display it
//otherwise display the generated name
if (strlen($DBGivenName) > 1) {
$FileName = $DBGivenName;
} else {
$FileName = $DBImageName;
}
$ProjectContent .= '
<img src="uploads/'.$DBLinkToThumb.'" width="150px" height="150px" alt="'.$FileName.'" title="'.$FileName.'"/>
';
//Finally we must construct the hyperlinks which will allow the user to select other pages. We will start with the links for any previous pages.
if ($pageno == 1) {
$FirstPrev = " FIRST PREV ";
} else {
$First = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=1'>FIRST</a> ";
$prevpage = $pageno-1;
$Prev = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$prevpage'>PREV</a> ";
}
//Next we inform the user of his current position in the sequence of available pages.
$PageNumb = " ( Page $pageno of $lastpage ) ";
//This code will provide the links for any following pages.
if ($pageno == $lastpage) {
$NextLast = " NEXT LAST ";
} else {
$nextpage = $pageno+1;
$Next = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$nextpage'>NEXT</a> ";
$Last = " <a href='{$_SERVER['PHP_SELF']}?page=project&id=$FormProjectID&pageno=$lastpage'>LAST</a> ";
}
}
}
Then in my html I have:
<div id="projectview">
<?php echo $ProjectContent; ?>
<?php echo $FirstPrev; ?>
<?php echo $First; ?>
<?php echo $Prev; ?>
<?php echo $PageNumb; ?>
<?php echo $NextLast; ?>
<?php echo $Next; ?>
<?php echo $Last; ?>
<div class="clear-div"></div>
</div>
This is outputing for example in this case 2 images, but the pagination links look like this:
FIRST PREV ( Page 1 of 0 ) NEXT LAST
Clicking on the links is not cycling through any other images, it still shows the same 2 images.
I can't figure out what I have done wrong here. I don't understand why it says "1 of 0" when clearly there should be more results.