jQuery selector to capture class inside php if statement - php

I'd like to make a selector to capture click events on code below :
index.php :
<ul class="pagination">
<?php
if ($page > 1) {
$link = $page - 1;
$prev = '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$link.','.$record_per_page.'">Previous</a></li>';
}else{
$prev = '<li class="page-item"><a class="page-link" href="javascript:void(0);">Previous</a></li>';
}
$num = '';
for($i = 1; $i<=$total_pages ; $i++){
if($i == $page){
$num .= '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$i.'">'.$i.'</a></li>';
}else{
$num .= '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$i.','.$record_per_page.'">'.$i.'</a></li>';
}
}
if ($page < $total_pages) {
$link = $page + 1;
$next = '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$link.','.$record_per_page.'">Next</a></li>';
}else{
$next = '<li class="page-item"><a class="page-link" href="javascript:void(0);">Next</a></li>';
}
echo $prev.$num.$next;
?>
</ul>
script.js :
$(document).on('click','.page-link',function () {
console.log('aaaaaa');
});
I already tried codes above, but it doesn't work, the console.log never showed up, is there any problem with my php code or jquery code ?

Thanks to all , and especially for Ritesh Khandekar, who gave me this code to solve my problem :
$(document).on('click','ul li .page-item',function() { console.log('aaaaaa'); });
I don't know why using page-item instead of page-link, but it workssss !!!!

Related

Could not get the id from the url when switching pages in pagination

I'm having trouble getting the id from the URL when i'm switching to another page using the pagination, I need this id from the database to view the contents in the navbar when i switch to another page. When I try to switch to pages the contents in the navbar will not appear. Here is my code
<?php
$limit = 5;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $limit;
$sql = "SELECT * FROM invoice LIMIT $start, $limit";
$result1 = $conn->query("SELECT count(id) AS refNo FROM invoice");
$query = mysqli_query($conn,$sql);
$custCount = $result1->fetch_all(MYSQLI_ASSOC);
$total = $custCount[0]['refNo'];
$pages = ceil($total / $limit);
$previous = $page - 1;
$next = $page + 1;
$id = $_GET['id2'];
?>
<h3 class="text-center" style="color:white">Student Schedules</h3>
<label for="course" style="color:white">Invoices And Records<br></label>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="viewUserSchedule.php?id=<?php $id?>&page=<?= $previous; ?
>">Previous</a></li>
<?php for($i = 1; $i <= $pages; $i++) : ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php $id?
>&page=<?= $i; ?>
"><?= $i ?></a></li>
<?php endfor; } ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php $id?
>&page=<?= $next; ?>">Next</a></li>
</ul>
</nav>
Just change this:
<?php $id?>
to this:
<?= $id ?>
or this:
<?php echo $id ?>
As I can see in your codes, you have simple mistake in your codes.
You are using:
<?php $id?>
and for other variables like $previous you are using:
<?= $previous; ?>
So <?= is shortcode for <?php echo and in printing your $id variable you missed the echo
So, you should use :
<?php echo $id?>
Or
<?= $id?>
so try this code, and it would work for you:
<h3 class="text-center" style="color:white">Student Schedules</h3>
<label for="course" style="color:white">Invoices And Records<br></label>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="viewUserSchedule.php?id=<?php echo $id?>&page=<?= $previous; ?>">Previous</a></li>
<?php for($i = 1; $i <= $pages; $i++) : ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php echo $id?>&page=<?= $i; ?>"><?= $i ?></a></li>
<?php endfor; } ?>
<li class="page-item"><a class="page-link" href="viewUserSchedule.php?id=<?php echo $id?>&page = <?= $next; ?>">Next</a></li>
</ul>
</nav>

issue when changing record limit in php dynamic pagination

I am learning PHP and was trying to created dynamic pagination to show record form MySQL.
The issue I'm facing is when I change number of record to be show by using SELECT tag it only works once after that it goes back to default value that i have set -> $limit = isset($_POST['records-count'])?$_POST['records-count']:"10"; which is 10.
PHP
include('../config/DbFunction.php');
$obj = new DbFunction();
$limit = isset($_POST['records-count'])?$_POST['records-count']:"10";
$page = isset($_GET['page'])? $_GET['page']:"1";
$start_data = ($page-1)*$limit;
$rs = $obj->view_course($limit,$start_data);
//print_r($limit); // to check limit value
$course_row = mysqli_fetch_row($obj->view_course1());
$total_records = $course_row[0];
$total_page = ceil($total_records/$limit);
$next = $page + 1 > $total_page? $total_page : $page +1;
$prev = $page - 1 == 0? 1 : $page - 1;
?>
Form
<form method="post" action="#">
Records: <select name="records-count" id="records_count">
<option disabled="disabled" selected="selected">Limit</option>
<?php foreach([20,50,100,200] as $limit): ?>
<option <?php if( isset($_POST["records_count"]) && $_POST["records_count"] == $limit) echo "selected" ?> value="<?= $limit; ?>"><?= $limit; ?></option>
<?php endforeach; ?>
</select>
</form>
Pagination
<div class="pagination">
<ul class="pagination pagination-default">
<li class='page-item'><a class='page-link' href="view-course.php?page=<?= $prev; ?>">Previous</a></li>
<?php
for ($i=1; $i<=$total_page; $i++) {
echo "<li class='page-item'><a class='page-link' href='view-course.php?page=".$i."'>".$i."</a></li>";
}
?>
<li class='page-item'><a class='page-link' href="view-course.php?page=<?= $next; ?>">Next</a></li>
</ul>
</div>
you may need to store and retrieve it from session. Session will allow to store variable in server
you need to start the session before send anything to client.
session_start();
if(isset($_POST['records-count']))
$_SESSION["records-count"] = $_POST['records-count'];
last thing to note is:
session variable will be updated in next requests.
After so many try I got the solution by using GET method
So i Change
$limit = isset($_POST['records-count'])?$_POST['records-count']:"10";
<div class="pagination">
<ul class="pagination pagination-default">
<li class='page-item'><a class='page-link' href="view-course.php?page=<?= $prev; ?>">Previous</a></li>
<?php
for ($i=1; $i<=$total_page; $i++) {
echo "<li class='page-item'><a class='page-link' href='view-course.php?page=".$i."'>".$i."</a></li>";
}
?>
<li class='page-item'><a class='page-link' href="view-course.php?page=<?= $next; ?>">Next</a></li>
</ul>
</div>
to
if (isset($_POST['records-count'])) {
$limit = $_POST['records-count'];
} else {
$limit = empty($_GET['records'])? "2":$_GET['records'];
}
<div class="pagination">
<ul class="pagination pagination-default">
<li class='page-item'><a class='page-link' href="view-course.php?page=<?= $prev; ?>&records=<?= $limit; ?>">Previous</a></li>
<?php
for ($i=1; $i<=$total_page; $i++) {
echo "<li class='page-item'><a class='page-link' href='view-course.php?page=".$i."& records=".$limit."'>".$i."</a></li>";
}
?>
<li class='page-item'><a class='page-link' href="view-course.php?page=<?= $next; ?>&records=<?= $limit; ?>">Next</a></li>
</ul>
</div>
If anyone know more efficient or better way then this plz let me know.

PHP: paging with Ajax not working correctly

I'm fetching records from a database and displaying them in gruops using php and ajax.
The script below (found somewhere) is almost working, but it seems that when you are on the first page and clicking "Next" you are taken to the LAST page.
Only when clicking the numbers individually, the paging is correct.
I can provide a test link in a PM if needed.
index.php:
<script>
$(document).ready(function() {
$("#results" ).load( "pages.php"); //load initial records
//executes code below when user click on pagination links
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
var page = $(this).attr("data-page"); //get page number from link
$("#results").load("pages.php",{"page":page}, function(){ //get content from PHP page
});
});
});
</script>
<div id="results"></div>
pages.php:
<?php
// continue only if $_POST is set and it is a Ajax request
if (isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
include (realpath(__DIR__ . '/../db.php'));
// Get page number from Ajax POST
if (isset($_POST["page"])) {
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
if (!is_numeric($page_number)) {
die('Invalid page number!');
}
}
else {
$page_number = 1; //if there's no page number, set it to 1
}
// get total number of records from database for pagination
$sql = "SELECT * FROM " . $DBtable . " ORDER BY dates DESC";
$rs = $conn->query($sql);
if ($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
else {
$get_total_rows = $rs->fetch_row(); //hold total records in variable
}
// break records into pages
$total_pages = ceil($get_total_rows[0] / $item_per_page);
// get starting position to fetch the records
$page_position = (($page_number - 1) * $item_per_page);
// Limit our results within a specified range.
$rs = $conn->prepare("SELECT id, title, description, dates, clicks FROM " . $DBtable . " ORDER BY dates DESC LIMIT $page_position, $item_per_page");
$rs->execute(); //Execute prepared Query
$rs->bind_result($id, $title, $description, $dates, $clicks); //bind variables to prepared statement
echo '<ul class="contents">';
while($rs->fetch()){ //fetch values
echo '<li>';
echo $id. '. <strong>' .$name.'</strong> — '.$description;
echo '</li>';
}
echo '</ul>';
echo '<div align="center">';
/* We call the pagination function here to generate Pagination link for us. */
echo paginate_function($item_per_page, $page_number, $get_total_rows[0], $total_pages);
echo '</div>';
exit;
}
// ############### pagination function #########################################
function paginate_function($item_per_page, $current_page, $total_records, $total_pages) {
$pagination = '';
if ($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages) { //verify total pages and current page number
$pagination.= '<ul class="pagination">';
$right_links = $current_page + 3;
$previous = $current_page - 3; //previous link
$next = $current_page + 1; //next link
$first_link = true; //boolean var to decide our first link
if ($current_page > 1) {
$previous_link = ($previous == 0) ? 1 : $previous;
$pagination.= '<li class="class="page-item" first"><a class="page-link" href="#" data-page="1" title="First">«</a></li>'; //first link
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $previous_link . '" title="Prev"><</a></li>'; //previous link
for ($i = ($current_page - 2); $i < $current_page; $i++) { //Create left-hand side links
if ($i > 0) {
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $i . '" title="Page' . $i . '">' . $i . '</a></li>';
}
}
//set first link to false
$first_link = false;
}
if ($first_link) { //if current active page is first link
$pagination.= '<li class="page-item active first"><a class="page-link" href="#">' . $current_page . '<span class="sr-only">(current)</span></a></li>';
}
elseif ($current_page == $total_pages) { //if it's the last active link
$pagination.= '<li class="page-item active last"><a class="page-link" href="#">' . $current_page . '<span class="sr-only">(current)</span></a></li>';
}
else { //regular current link
$pagination.= '<li class="page-item active"><a class="page-link" href="#">' . $current_page . '<span class="sr-only">(current)</span></a></li>';
}
for ($i = $current_page + 1; $i < $right_links; $i++) { //create right-hand side links
if ($i <= $total_pages) {
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $i . '" title="Page ' . $i . '">' . $i . '</a></li>';
}
}
if ($current_page < $total_pages) {
$next_link = ($i > $total_pages) ? $total_pages : $i;
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $next_link . '" title="Next">></a></li>'; //next link
$pagination.= '<li class="page-item last"><a class="page-link" href="#" data-page="' . $total_pages . '" title="Last">»</a></li>'; //last link
}
$pagination.= '</ul>';
}
//return pagination links
return $pagination;
}
// Free memory
$rs->free();
// Close connection
$conn->close();
?>
This is the current parsed html of the pager:
<ul class="pagination">
<li class="page-item active first"><a class="page-link" href="#">1<span class="sr-only">(current)</span></a></li>
<li class="page-item"><a class="page-link" href="#" data-page="2" title="Page 2">2</a></li>
<li class="page-item"><a class="page-link" href="#" data-page="3" title="Page 3">3</a></li>
<li class="page-item"><a class="page-link" href="#" data-page="4" title="Next">></a></li>
<li class="page-item last"><a class="page-link" href="#" data-page="4" title="Last">»</a></li>
</ul>
just try like below in your paginate_function()
$next_link = ($i > $total_pages) ? $total_pages : $i;
to
$next_link = (($current_page + 1) > $total_pages) ? $total_pages : $current_page + 1;
Please make changes in paginate_function function as below
if ($current_page < $total_pages) {
$next_link = ($i > $total_pages) ? $total_pages : $i;
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $next_link . '" title="Next">></a></li>'; //next link
$pagination.= '<li class="page-item last"><a class="page-link" href="#" data-page="' . $total_pages . '" title="Last">»</a></li>'; //last link
}
Change this to
if ($current_page < $total_pages) {
$next_link = ($i > $total_pages) ? $total_pages : $next;
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $next_link . '" title="Next">></a></li>'; //next link
$pagination.= '<li class="page-item last"><a class="page-link" href="#" data-page="' . $total_pages . '" title="Last">»</a></li>'; //last link
}

PHP Pagination Display

I'm using bootstrap pagination, and a combination PHP/mysql method of displaying my results, (ex. results.php?results=1 for each page). This is working fine, but actually displaying the pagination div at the bottom of my page, i.e. which one is active, whether or not you can click the following or preceding items (if there actually are results on those pages)
So I've done a specific case for just about every combination I could think of that would affect anything, but it is certainly not efficient. Can anyone suggest a better way to do it? Some of the cases will be obvious, like if I'm on page one, I don't want to show page 0 and -1 in the pagination, others are less obvious, like if I'm on page 3, and there are no more pages, I want page 3 to be in the middle, as there are 5 numbers displayed, but you should not be able to click on 4 and 5.
I'm using an exact replica of the plugin showed here except I've added left and right increase / decrease by one in addition to the first / last page.
<div id="pagination" style="width: 340px; margin-left: auto; margin-right: auto;">
<? if ($results == 1) { ?>
<ul class="pagination">
<li class="disabled"> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li class="disabled"> <i class="fa fa-lg fa-angle-left"></i> </li>
<li class="active"><? echo $results; ?> <span class="sr-only">(current)</span></li>
<li <?if ($num_rows < $num_res) { echo "class=\"disabled\""; } ?>><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 2)) { echo "class=\"disabled\""; } ?>><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 3; ?></li>
<li <?if ($num_rows < ($num_res * 4)) { echo "class=\"disabled\""; } ?>><? echo $results + 4; ?></li>
<li <?if ($num_rows < ($num_res)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if ($results == 2) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results; ?> <span class="sr-only">(current)</span></li>
<li <?if ($num_rows < ($num_res * 2)) { echo "class=\"disabled\""; } ?>><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 3; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results == 3) && (($last_page == 3))) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 2; ?> </li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results; ?><span class="sr-only">(current)</span></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results > 2) && ($results < ($last_page - 1))) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 2; ?> </li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results; ?><span class="sr-only">(current)</span></li>
<li><? echo $results + 1; ?></li>
<li><? echo $results + 2; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results > 2) && ($results == ($last_page - 1))) { ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 3; ?></li>
<li><? echo $results - 2; ?></li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results ?><span class="sr-only">(current)</span></li>
<li><? echo $results + 1; ?></li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-right"></i> </li>
<li <?if ($num_rows < ($num_res * 3)) { echo "class=\"disabled\""; } ?>> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
<? if (($results > 2) && ($results == $last_page) && ($results != 3)){ ?>
<ul class="pagination">
<li> <i class="fa fa-lg fa-angle-double-left"></i> </li>
<li> <i class="fa fa-lg fa-angle-left"></i> </li>
<li><? echo $results - 4; ?> </li>
<li><? echo $results - 3; ?></li>
<li><? echo $results - 2; ?></li>
<li><? echo $results - 1; ?></li>
<li class="active"><? echo $results ?><span class="sr-only">(current)</span></li>
<li class="disabled"> <i class="fa fa-lg fa-angle-right"></i> </li>
<li class="disabled"> <i class="fa fa-lg fa-angle-double-right"></i> </li>
</ul>
<? } ?>
</div>
If no one feels like helping with the first portion, I understand, it works as it is as far as I can tell.
But I also am wondering if there's a way that on my class="disabled", I can remove the hrefs? Or do I just have to put an if statement on every one? Thanks.
Edit: Based on #Scopey's recommendations. I changed a few things as I saw fit, as well as a couple variable names.
$numberOfPages = ceil($num_rows / $num_res);
$numberOfPages = (int)$numberOfPages;
$url = explode('&', $_SERVER['REQUEST_URI']);
function myFilter($string) {
return strpos($string, 'results=') === false;
}
$url = array_filter($url, 'myFilter');
$url = implode('&', $url);
?>
<ul class="pagination">
<li<?php if($results === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== $numberOfPages){
echo $url.'&results=' . 1;
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-double-left"></i> </a></li>
<li<?php if($results === 1): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== 1){
echo $url.'&results=' . ($results - 1);
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-left"></i> </a></li>
<?php
// Print the pagination...
// Minimum of 5 pages in the pagination, even if there aren't 5 pages...
$pageCount = ($numberOfPages < 5) ? 5 : $numberOfPages;
// Loop through from page 1 until the last page ($pageCount)
for($i = 1; $i <= $pageCount; $i++)
{
// Echo out just the beginning of the <li> tag as we don't yet
// know if this needs to be disabled...
echo '<li';
// Added to show if current page is active
if($i === $results) {
echo ' class="active"';
}
// Check if:
// - This current page is greater than the amount of pages of
// results we have
// - OR, this is the currently selected page
if($i > $numberOfPages || $results === $i)
{
// <li> tag needs the disabled class....
echo ' class="disabled"';
}
// Finish the <li> tag and start generating the link
echo '><a href="';
// Opposite logic from above... Only if this is a page we know about
// AND this is not the current page.
if($i < $numberOfPages && $results !== $i)
{
// The link will be your page, with the get param, and the
// current page number we're printing
echo $url.'&results=' . $i;
}
else
{
// Otherwise just a # (no link)
echo '#';
}
// Finish this page... Print the page number ($i)
echo '">' . $i . '</a></li>';
}
?>
<li<?php if($results === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== $numberOfPages){
echo $url.'&results=' . ($results + 1);
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-right"></i> </a></li>
<li<?php if($results === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($results !== $numberOfPages){
echo $url.'&results=' . $numberOfPages;
} else { echo '#'; }
?>"> <i class="fa fa-lg fa-angle-double-right"></i> </a></li>
<?php
#Scobey, this works great, as intended, and same as my original post, except for a couple things. In my example, I was able to get the current page in the middle of the . For example, << 1 | 2 | 3 | 4 | 5 >>, that's why I had so many different statements with +1 and -1, +2, -2 etc.
Second, my intention was to display 5 page options at all times, not just a minimum of five. So if I was on page 6, I would only see << 4 | 5 | 6 | 7 | 8 >>, not 1-8. It may not be necessary to do it this way, it's a nice to have. But, I don't want to get to a point where I have over 50 different page numbers in the pagination.
Generally dynamic pagination works only when you have a few things
A count of all possible results (total)
An amount of results you want to show per page
The current page number
Information about the results that should appear on this page.
Imagine that you have a database table called Results that has a whole bunch of results you want on your paginated page
1. Count of all possible results
This is achievable with a simple SQL statement like:
SELECT count(*) FROM Results
2. Amount per page
This is a value you get to decide yourself.
3. The current page number
This is usually 1 by default, but when the pagination is changed, it gets passed through as a get parameter.
4. A slice of results from the table
Achievable with:
SELECT * FROM Results LIMIT 0, 20
This example retrieves the first 20 results in our results table...
5. The pagination
Now, using 20 results as a default "count per page"
$countPerPage = 20;
// Get the total number of results
$result = pg_query('SELECT count(*) FROM Results'); // I'm using PostgreSQL for this example
$totalResultCount = (int)pg_fetch_result($result, 0, 0);
// The ceil function will round floats up.
$numberOfPages = ceil($totalResultCount / $countPerPage);
// Check if we have a page number in the _GET parameters
if(!empty($_GET) && isset($_GET['page']))
{
$page = (int)$_GET['page'];
}
else
{
$page = 1;
}
// Check that the page is within our bounds
if($page < 0)
{
$page = 1;
}
elseif($page > $numberOfPages)
{
$page = $numberOfPages;
}
// Build the query for the results...
$query = 'SELECT * FROM Results LIMIT ' . ($page - 1) * $countPerPage . ', ' . $countPerPage;
$results = pg_fetch_all(pg_query($query));
// Deal with printing your results etc...
?>
<ul class="pagination">
<li<?php if($page === 1): ?> class="disabled"<?php endif; ?>><a href="<?php
if($page !== 1){
echo 'page.php?page=' . $page - 1;
} else { echo '#'; }
?>">«</a></li>
<?php
// Print the pagination...
// Minimum of 5 pages in the pagination, even if there aren't 5 pages...
$pageCount = ($numberOfPages < 5) ? 5 : $numberOfPages;
// Loop through from page 1 until the last page ($pageCount)
for($i = 1; $i < $pageCount; $i++)
{
// Echo out just the beginning of the <li> tag as we don't yet
// know if this needs to be disabled...
echo '<li';
// Check if:
// - This current page is greater than the amount of pages of
// results we have
// - OR, this is the currently selected page
if($i > $numberOfPages || $page === $i)
{
// <li> tag needs the disabled class....
echo ' class="disabled"';
}
// Finish the <li> tag and start generating the link
echo '><a href="';
// Opposite logic from above... Only if this is a page we know about
// AND this is not the current page.
if($i < $numberOfPages && $page !== $i)
{
// The link will be your page, with the get param, and the
// current page number we're printing
echo 'page.php?page=' . $i;
}
else
{
// Otherwise just a # (no link)
echo '#';
}
// Finish this page... Print the page number ($i)
echo '">' . $i . '</a></li>';
}
?>
<ul class="pagination">
<li<?php if($page === $numberOfPages): ?> class="disabled"<?php endif; ?>><a href="<?php
if($page !== $numberOfPages){
echo 'page.php?page=' . $page + 1;
} else { echo '#'; }
?>">»</a></li>
<?php
Disclaimer
I just sat here and wrote this, I have not tested it, but the general idea is there. Hopefully it makes sense. I'm running out of time and don't have time to test or improve it, but if you're interested I might fix it up later.
Hope this helps!

Selecting every 3rd item starting after the 2nd

I have the following code:
$loop = 0;
$columns = 3;
<?php while ( have_posts() ) :
the_post();
$loop++;
?>
<li class="<?php if ( $loop % $columns == 0) echo 'last'; if ( ( $loop - 1 ) % $columns == 0 ) echo 'first'; ?>">
</li>
What I want to achieve is:
<li class="first"></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
What I am getting is (which makes sense..):
<li class="first"></li>
<li class="=""></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
meaning the first 2 are given the class first and last respectively and after that it is every 3.
If i was able to use css I would say nth-child(3n+2) but I can't because I want to assign a new class, and I can only assign a style with css.
How can I achieve it with php?
The following will generate the code that you gave as an example:
<?php
$loop = 0;
$offset = 2;
while ($loop < 100) {
echo '<li class="';
if ($loop < $offset) {
if ($loop % 2 == 0) {
echo 'first';
} else {
echo 'last';
}
} else {
if (($loop - $offset) % 3 == 0) {
echo 'first';
} elseif (($loop - $offset + 2 ) % 3 == 0) {
echo '';
} else {
echo 'last';
}
}
echo '"></li>';
++$loop;
}
If the $loop variable is under the offset it print first and last alternately otherwise it will check divisibility with 3, giving the dividend an extra offset for each condition so they will be true sequentially.

Categories