Integrating pagination into mysql query - php

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.

Related

Pagination only showing first 10 results instead of x amount of pages with 10 results on each

I have a piece of PHP code that is supposed to loop through all the results and make a new page for every 10 results, however it only shows the first 10 results and no options of next page or page numbers.
Is there a reason for this or have I missed something in the code I have written?
Thanks in advance.
My code is below;
$search_course = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_course) or die($mysqli->error);
$search_result = $result->fetch_assoc();
$row = mysqli_fetch_row($result);
//total rows for search
$rows = $row[0];
//number of results per page
$rows_per_page = 10;
//shows last page
$last_page = ceil($rows/$rows_per_page);
if($last_page < 1){
$last_page = 1;
}
$page_number = 1;
if(isset($_GET['pn'])){
$page_number = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
//makes sure page number is between limits of $page_number
if($page_number < 1){
$page_number = 1;
} else if($page_number > $last_page){
$page_number = $last_page;
}
// sets the value of items to view
$limit = 'LIMIT ' .($page_number -1) * $rows_per_page .',' .$rows_per_page;
// query again only grabbing the set number of rows depending on page number
$search_course = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'
ORDER BY title DESC $limit";
$result = $mysqli->query($search_course) or die($mysqli->error);
$search_result = $result->fetch_assoc();
//displays to the user the total number of results and the page numbers
$total_number_of_results = "Search Results (<b>$rows</b>)";
$page_user_is_on = "Page <b>$page_number</b> of <b>$last_page</b>";
//set up pagination
$pagination_controls = '';
if($last_page != 1){
if($page_number > 1){
$previous = $page_number - 1;
$pagination_controls .='previous ';
for($i = $page_number - 4; $i < $page_number; $i++)
{
if($i > 0){
$pagination_controls .= ''.$i.' ';
}
}
}
$pagination_controls.=''.$page_number.' &nbsm; ';
//clickable links to the left
for($i = $page_number+1; $i <= $last_page; $i++)
{
$pagination_controls .= ''.$i.' ';
if($i >= $page_number+4){
break;
}
}
if($page_number != $last){
$next = $page_number + 1;
$pagination_controls.=' Next';
}
}
$list = '';
while($row = mysqli_fetch_array($result)){
$title = $row['title'];
$id = $row['id'];
$list.='<p><a href="Selectedcourse.php">'.$title.' </p>';
}
mysqli_close($mysqli);
and the html element;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='courses.css'>
</head>
<body>
<div class="header">
<h1>Search Results for - <?= $_POST['searchBar'] ?></h1>
</div>
<div>
<h3> <?php echo $page_user_is_on ?> </h3>
<p><?php echo $list; ?></p>
<p><?php echo $search_result['summary']; ?> </p>
</div>
<div id="pagination_controls"><?php echo $pagination_controls; ?></div>
</body>
</html>
This is a good effort to roll your own pagination. It was mostly working. The problem was in your first query here:
$search_result = $result->fetch_assoc();
//This fetches only the first row of results
$row = mysqli_fetch_row($result);
//So this is not the total rows for search
$rows = $row[0];
Here's an updated script using prepared statements, which you really need to use. Unless you love being hacked.
//turn errors on to develop, back off when you go live
error_reporting(E_ALL);
ini_set('display_errors', 1);
//here are my main changes
$search_param = "%" . $_POST['searchBar'] . "%";
$stmt = $mysqli->prepare("SELECT title, summary, id FROM course WHERE title LIKE ?");
$stmt->bind_param("s", $search_param); //learn this
$stmt->execute();
$result = $stmt->get_result();
//This gets the number of rows in a query result
$rows = $result->num_rows;
//number of results per page
$rows_per_page = 10;
//shows last page
$last_page = ceil($rows/$rows_per_page);
if($last_page < 1){
$last_page = 1;
}
if(isset($_GET['pn'])){
$page_number = preg_replace('#[^0-9]#', '', $_GET['pn']);
} else {
$page_number = 1;
}
//makes sure page number is between limits of $page_number
if($page_number < 1){
$page_number = 1;
} else if($page_number > $last_page){
$page_number = $last_page;
}
// sets the value of items to view
$limit = 'LIMIT ' .($page_number -1) * $rows_per_page .',' .$rows_per_page;
//displays to the user the total number of results and the page numbers
$total_number_of_results = "Search Results (<b>$rows</b>)";
$page_user_is_on = "Page <b>$page_number</b> of <b>$last_page</b>";
//query again only grabbing the set number of rows depending on page number
$stmt = $mysqli->prepare("SELECT title, summary, id FROM course WHERE title LIKE ? ".$limit);
$stmt->bind_param("s", $search_param);
$stmt->execute();
$result = $stmt->get_result();
$list = '';
while($row = $result->fetch_assoc()){
$title = $row['title'];
$id = $row['id'];
//I'm assuming you want each link to be different here...
$list.='<p>' . $title . '</p>';
}
mysqli_close($mysqli);
//set up pagination
$pagination_controls = '';
if($last_page != 1){
if($page_number > 1){
$previous = $page_number - 1;
$pagination_controls .='previous ';
for($i = $page_number - 4; $i < $page_number; $i++)
{
if($i > 0){
$pagination_controls .= ''.$i.' ';
}
}
}
$pagination_controls.=''.$page_number.' ';
//clickable links to the left
for($i = $page_number+1; $i <= $last_page; $i++)
{
$pagination_controls .= ''.$i.' ';
if($i >= $page_number+4){
break;
}
}
if($page_number != $last_page){
$next = $page_number + 1;
$pagination_controls.=' Next';
}
}
And finally the HTML section, with only one change:
<div class="header">
<h1>Search Results for - <?= $_POST['searchBar'] ?></h1>
</div>
<div>
<h3> <?php echo $page_user_is_on ?> </h3>
<p><?php echo $list; ?></p>
<p><?php /* echo $search_result['summary']; //Where was this coming from? */?> </p>
</div>
<div id="pagination_controls"><?php echo $pagination_controls; ?></div>

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
}

show page numbering in PHP

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 ';
?>

PHP/MySQL - Pagination with variety of ORDER BY clauses

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).

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