PHP/MySQL - Pagination with variety of ORDER BY clauses - php

I have the following queries: the first as a count for pagination, the second to fill the resulting table with data. They both worked very well, but I want to add Ordering functionality to the table also, and have made some ham-fisted efforts in that direction.
Essentially, I have broken up the MySQL query into portions stored in variables, which may or may not be assigned based on the wishes of the user as expressed by the submitting and GETting of forms. I'm only at a beginner level, and this is what made logical sense to me. It is probably not the correct method!
The data is ordered by default as it is entered in the database. The table is filled 15 rows at a time. Ideally, the user could then choose to order the animal's data in another way - by age, or colour, for example. The choice is made via submitting a form to the page itself, the query is re-submitted, and the result is outputted in 15-row pages again.
So far, here is my code:
PAGINATION:
$genderid = $_GET['groupid'];
$sortby = $_GET['sortby'];
##################
if (isset($_GET['pageno'])) { $pageno = $_GET['pageno']; }
else { $pageno = 1; }
$initialcount = "SELECT count(*)
FROM profiles
WHERE ProfileName != 'Unknown'";
if ($genderid > 0) {
$genderquery = " AND ProfileGenderID = $genderid";
}
if ($sortby == 'age') {
$orderby = " ORDER BY ProfileYearOfBirth ASC";
}
elseif ($sortby == 'colour') {
$orderby = " ORDER BY ProfileAdultColourID ASC";
}
$finalcount = ($initialcount . ' ' . $genderquery . ' ' . $orderby);
$result = mysql_query($finalcount) or trigger_error();
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 15;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
if ($pageno == 1)
{
echo '<p class="pagination">';
echo '<span class="first"><< First</span><span class="previous">< Previous</span>';
}
else
{
echo '<p class="pagination">';
echo "<span class='first'><a href='{$_SERVER['PHP_SELF']}?pageno=1'><< First</a></span>";
$prevpage = $pageno-1;
echo "<span id='class'><a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage'>< Previous</a></span>";
}
echo '<span class="pagination-nav">' . "Page $pageno of $lastpage" . '</span>';
if ($pageno == $lastpage)
{
echo '<span class="next">Next ></span><span class="last">Last >></span>';
echo '</p>';
}
else
{
$nextpage = $pageno+1;
echo "<span class='next'><a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage'>Next ></a></span>";
echo "<span class='last'><a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage'>Last >></a></span>";
echo '</p>';
}
OUTPUT:
<table class="admin-display">
<thead>
<tr>
<th>Name:</th>
<th>Age:
<form class="sorting-form" method="GET" action="">
<input type="hidden" name="sortby" value="age" />
<input type="hidden" name="groupid" value="<?php echo $genderid; ?>" />
<input type="submit" value="⇑" class="sort-submit" />
</form>
</th>
<th>Colour:
<form class="sorting-form" method="GET" action="">
<input type="hidden" name="sortby" value="colour" />
<input type="hidden" name="groupid" value="<?php echo $genderid; ?>" />
<input type="submit" value="⇑" class="sort-submit" />
</form>
</th>
<th>Gender:</th>
<th>Owner:</th>
<th>Breeder:</th>
</tr>
</thead>
<?php
$initialquery = "SELECT ProfileID, ProfileOwnerID, ProfileBreederID,
ProfileGenderID, ProfileAdultColourID, ProfileColourModifierID, ProfileYearOfBirth,
ProfileYearOfDeath, ProfileLocalRegNumber, ProfileName,
owner.ContactFirstName AS owner_fname, owner.ContactLastName AS owner_lname,
breeder.ContactFirstName AS breeder_fname, breeder.ContactLastName AS breeder_lname,
BreedGender, BreedColour, BreedColourModifier
FROM profiles
LEFT JOIN contacts AS owner
ON ProfileOwnerID = owner.ContactID
LEFT JOIN contacts AS breeder
ON ProfileBreederID = breeder.ContactID
LEFT JOIN prm_breedgender
ON ProfileGenderID = prm_breedgender.BreedGenderID
LEFT JOIN prm_breedcolour
ON ProfileAdultColourID = prm_breedcolour.BreedColourID
LEFT JOIN prm_breedcolourmodifier
ON ProfileColourModifierID = prm_breedcolourmodifier.BreedColourModifierID
WHERE ProfileName != 'Unknown'";
$finalquery = ($initialquery . ' ' . $genderquery . ' ' . $orderby . ' ' . $limit);
$result = mysql_query($finalquery) or trigger_error("SQL", E_USER_ERROR);
//process results
The data still outputs correctly (initially), and the user can re-submit the query successfully also. The problem arises when - after ordering by anything other than default - I click to go forward a page. Once the page changes, the ordering returns to default. I don't know how to maintain that ORDER BY clause beyond the initial re-submission.
This is as far as I've gotten before I start breaking the code and things begin to get hairy. I need someone to point out the glaring error! Much thanks in advance :)

This sounds like it should be handled in an AJAX call. Theoretically, you can persist your initial and incremented state throughout the session (using the session variable, a hidden form field, or even a cookie) but I think you'll be happier with asynchronously grabbing X records at a time and keeping the arguments on the client side until you want to get the next page.
Per poster's inquiry, storing the necessary values in the session would look something like this:
session_start();
$startat = intval($_REQUEST["startat"]);
$numrows= intval($_REQUEST["numrows"]);
if (isset($_SESSION['base_query'])){
$query = $_SESSION['base_query'];
} else {
$query = <query construction minus limit clause>;
$_SESSION['base_query'] = $query;
}
$query .= " LIMIT $startat, $numrows";
<query db/ send results>
Does that give you the idea?

maybe you can get around this problem by using http://www.datatables.net/ ? it's a client side ajax solution that orders results for you. And you avoid reloading the whole page each time.

Ok, I worked on what I had for another few hours, and came up with a solution. It doesn't use AJAX, or SESSIONS, and is undoubtably horrible to behold, but it suits the skill level I'm at.
First off, I changed the pagination script to give a distinct value to the offset parameter:
$title = intval($_GET['groupid']);
$genderid = intval($_GET['groupid']);
$sortby = $_GET['sortby'];
##################################
$initialcount = "SELECT count(*) FROM profiles WHERE ProfileName != 'Unknown'";
if($genderid > 0) {
$where = "AND ProfileGenderID = $genderid";
$finalcount = ($initialcount . ' ' . $where);
}
else { $finalcount = $initialcount; }
$result = mysql_query($finalcount) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
$rowsperpage = 15;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
}
else { $currentpage = 1; }
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1)
{ $currentpage = 1; }
$offset = ($currentpage - 1) * $rowsperpage;
I also changed the pagination links to a) hold the value of the current gender (overall) sort, and the subsequent sort (age, colour); and b) to display numbered page links á la Google:
// range of num links to show
$range = 3;
##############
$range = 3;
echo '<p class="pagination">';
if ($currentpage == 1)
{
echo '<span class="first"><< First</span><span class="previous">< Previous</span>';
}
if ($currentpage > 1) {
echo "<span class='first'><a href='{$_SERVER['PHP_SELF']}?sortby=$sortby&groupid=$genderid&currentpage=1'><< First</a></span>";
$prevpage = $currentpage - 1;
echo "<span class='previous'><a href='{$_SERVER['PHP_SELF']}?sortby=$sortby&groupid=$genderid&currentpage=$prevpage'>< Previous</a></span>";
}
echo '<span class="pagination-nav">';
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " [<b>$x</b>] ";
}
else {
echo " <a href='{$_SERVER['PHP_SELF']}?sortby=$sortby&groupid=$genderid&currentpage=$x'>$x</a> ";
}
}
}
echo '</span>';
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo "<span class='next'><a href='{$_SERVER['PHP_SELF']}?sortby=$sortby&groupid=$genderid&currentpage=$nextpage'>Next ></a></span>";
echo "<span class='last'><a href='{$_SERVER['PHP_SELF']}?sortby=$sortby&groupid=$genderid&currentpage=$totalpages'>Last >></a></span>";
}
if ($currentpage == $totalpages)
{
echo '<span class="next">Next ></span><span class="last">Last >></span>';
}
echo '</p>';
And finally constructed the query:
$baseQuery = "SELECT ProfileID, ProfileOwnerID, ProfileBreederID,
ProfileGenderID, ProfileAdultColourID, ProfileColourModifierID, ProfileYearOfBirth,
ProfileYearOfDeath, ProfileLocalRegNumber, ProfileName,
owner.ContactFirstName AS owner_fname, owner.ContactLastName AS owner_lname,
breeder.ContactFirstName AS breeder_fname, breeder.ContactLastName AS breeder_lname,
BreedGender, BreedColour, BreedColourModifier
FROM profiles
LEFT JOIN contacts AS owner
ON ProfileOwnerID = owner.ContactID
LEFT JOIN contacts AS breeder
ON ProfileBreederID = breeder.ContactID
LEFT JOIN prm_breedgender
ON ProfileGenderID = prm_breedgender.BreedGenderID
LEFT JOIN prm_breedcolour
ON ProfileAdultColourID = prm_breedcolour.BreedColourID
LEFT JOIN prm_breedcolourmodifier
ON ProfileColourModifierID = prm_breedcolourmodifier.BreedColourModifierID
WHERE ProfileName != 'Unknown'";
if($sortby == 'age') {
$orderby = "ORDER BY ProfileYearOfBirth ASC";
}
elseif ($sortby == 'colour') {
$orderby = "ORDER BY ProfileAdultColourID ASC";
}
$limitClause = "LIMIT $offset, $rowsperpage";
$finalQuery = ($baseQuery . ' ' . $where . ' ' . $orderby . ' ' . $limitClause);
$result = mysql_query($finalQuery) or trigger_error("SQL", E_USER_ERROR);
Effective as a hammer hitting a cheesecake :)
Much thanks to the contributors above, particularly for introducing me to INTVAL (and by progression, CASTING).

Related

Can we display table records in multiple pages using POST?

I have a form that uses the method post. The form contains a submit button and on clicking it, my database records get displayed in an html table. I would like to limit the number of rows (5) displayed to each page, but I'm not looking to use GET. Is there any way I can do that with my post method?
// My form using post method
<form action = "" name = "dealer_call_log.php" id = "dealer_call_log.php" method = "post">
//Data displayed in the table below from post
$record_per_page = 5;
$page = '';
if(isset($_GET['page'])){
$page = $_GET['page'];
}
else{
$page = 1;
}
$start_from = ($page - 1) * $record_per_page;
if(isset($_POST['submit'])){
echo '<center>';
echo '<br>';
$sql = "SELECT SFID, Comment, Time FROM tbl_call_log_detail
WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='')
ORDER BY Time DESC LIMIT $start_from, $record_per_page" ;
$result = mysqli_query($conn, $sql);
$rows = mysqli_num_rows($result);
$all_property = array();
echo "<table class = 'data-table' border = '1' cellpadding = '9' bgcolor = '#CCCCCC'>
<tr class = 'data-heading'>";
while($property = mysqli_fetch_field($result)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property, $property ->name);
}
echo '</tr>';
}
while ($row = mysqli_fetch_array($result)){
echo '<tr>';
foreach($all_property as $item){
echo '<td> '. $row[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
}
$page_query = "SELECT * FROM tbl_call_log_detail ";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
$start_loop = $page;
$difference = $total_pages - $page;
if($difference <= $total_pages){
$start_loop = $total_pages - $difference;
}
$end_loop = $start_loop + 2;
if($difference > $total_pages){
$end_loop = $total_pages;
}
if($page > 1){
echo "<a href= 'dealer_call_log.php?page=1'>First</a>";
echo "<a href= 'dealer_call_log.php?page=".($page - 1)."'><<</a>";
}
for ($i = $start_loop; $i <= $end_loop; $i++){
echo "<a href= 'dealer_call_log.php?page=".$i."'>".$i."</a>";
}
if($page <= $end_loop){
echo "<a href= 'dealer_call_log.php?page=".($page + 1)."'>>></a>";
echo "<a href= 'dealer_call_log.php?page=".$total_pages."'>Last</a>";
}
if($page < 1){
$page = 1;
}
echo '</table>';
Any help would be appreciated. Thanks!
You can use LIMIT 20 OFFSET 0 to get the first 20 results. Then for the next page you can use LIMIT 20 OFFSET 20 the get the second set of 20 results. See W3Schools for more information on this
You can also keep track of your pagenumber with post but you'll have to post it in an input field. You can use an input type hidden like so: <input type="hidden" name="pageNumber" value="0"> and change the value everytime you switch page.
Then you could do something like this:
$limit = 20;
if(isset($_POST['pageNumber']) {
$page = $_POST['pageNumber'];
} else {
$page = 0;
}
$sql = "SELECT sfid, comment, time_stamp, time_of_submission FROM tbl_call_log_detail
WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( time_stamp <= '$endDate' AND time_stamp >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='')
ORDER BY time_stamp DESC
LIMIT " . $limit . " OFFSET " . $page * $limit;
echo '<input type="hidden" name="pageNumber" value="' . $page + 1 . '">'

Pagination Prev - Next Increment

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
}

Sorting is not working with LIMIT while fetching results

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

Integrating pagination into mysql query

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.

Small Issue PHP Pagination Mathematics Help

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 (....) {
.....
}

Categories