am using following function to display pagination
public function paginationLinks(){
$outputString = "";
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
return $outputString;
}
and this is how i display
<ul class="pagination pagination-sm">
<?php echo $news->paginationLinks(); ?>
</ul>
now bootstrap doesn't display active page its because of function
how do i add some more option like next, previous and :active
just replace your function with this one
public function paginationLinks(){
$outputString = "";
$crpage = isset($_GET['page']) && trim($_GET['page']) != ''?trim($_GET['page']):1;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$newsNumber = $res[0];
$q->closeCursor();
for($i = 1; $i <= ceil($newsNumber / $this->newsByPage); $i++){
if($crpage == $i){
$outputString .="<li class='active'><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}else{
$outputString .="<li><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
}
return $outputString;
}
For next or previous see that link
great example for PHP pagination.
Please try this .I hope this help you
public function paginationLinks(){
$num_rec_per_page = 10;
$outputString = "";
$page = (isset($_GET['page']) && $_GET['page'] != '') ? trim($_GET['page']) : 1;
$start_from = ($page-1) * $num_rec_per_page;
$q = $this->db->query('SELECT COUNT(*) FROM videos');
$res = $q->fetch();
$total_records = $res[0];
$q->closeCursor();
$total_pages = ceil($total_records / $num_rec_per_page);
$outputString .= "<li><a href='?page=1'>".'|<'."</a></li>"; // Goto 1st page
if($page > 1){
$prev = $page - 1;
$outputString .= "<li><a href='?page=".$prev."'>Prev</a></li>"; // Goto previous page
}
for ($i=1; $i<=$total_pages; $i++) {
$activeClass = ($page == $i) ? 'active' : '';
$outputString .="<li class=".$activeClass."><a href='?page=" . $i . "'>" . $i . "</a></li> ";
}
if($page < $total_pages){
$next = $page + 1;
$outputString .= "<li><a href='?page=".$next."'>Next</a></li>"; // Goto Next page
}
if($page > 1){
$outputString .= "<li><a href='?page=".$total_pages."'>".'|>'."</a></li>"; // Goto last page
}
return $outputString;
}
Related
So I have these two PHP files products.php and receive.php .
What my problem is I want to use Ajax on displaying the products with search and paginates also. The code below works though but only if I use a GET. Is it possible to submit only the page number and refreshes only the div (where products loop) and not the whole page so that my POST requests (from search values - title, keywords) will still hold? coz if I use GET on pagination, the POST requests are getting empty after clicking the second page.
receive.php
$pdo_sql = 'SELECT * FROM items WHERE item_title LIKE %$keyword% OR keywords LIKE %$keyword% ORDER BY id DESC ';
/*** Pagination Code starts ***/
$per_page_html = '';
$page = 1;
$start=0;
// Get Page Number
if(!empty($_GET["page"])) {
$page = $_GET["page"];
$start=($page-1) * ROW_PER_PAGE;
}
// Adds Limit to Query then Execute
$limit=" LIMIT " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($pdo_sql);
$pagination_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
// Count the total number of rows
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$total_links=ceil($row_count/ROW_PER_PAGE);
$previous_link = $next_link = $page_link = '';
if($total_links > 4)
{
if($page < 5)
{
for($count = 1; $count <= 5; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
else
{
$end_limit = $total_links - 5;
if($page > $end_limit)
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $end_limit; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
else
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $page - 1; $count <= $page + 1; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
}
}
else
{
for($count = 1; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
for($count = 0; $count < count($page_array); $count++)
{
if($page == $page_array[$count])
{
// Current Page = Selected Page
$page_link .= '<a class="paginate_current" href="javascript:void(0)">'.$page_array[$count].'</a>';
$previous_id = $page_array[$count] - 1;
if($previous_id > 0)
{
// Previous Button Enable
$previous_link = '<a class="paginate_prev" href="products.php?page='.$previous_id.'">Previous</a>';
}
else
{
// Previous Button Disabled
$previous_link = '<a class="paginate_prev-disabled" href="javascript:void(0)">Previous</a>';
}
$next_id = $page_array[$count] + 1;
if($next_id > $total_links)
{
// Next Button Disabled
$next_link = '<a class="paginate_next-disabled" href="javascript:void(0)">Next</a>';
}
else
{
// Next Button Enabled
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
}
}
else
{
if($page_array[$count] == '...')
{
// Ellipsis
$page_link .= '<a class="paginate_ellipsis" href="javascript:void(0)">...</a>';
}
else
{
// Pages
$page_link .= '<a class="paginate_pages" href="products.php?page='.$page_array[$count].'">'.$page_array[$count].'</a>';
}
}
}
$per_page_html .= '<div class="text-center paginate">';
$per_page_html .= $previous_link . $page_link . $next_link;
$per_page_html .= '</div>';
}
$query = $pdo_sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$pdo_result = $pdo_statement->fetchAll();
products.php
<div class="row">
<div class="col">
<div class="products_container grid" id="refresh">
<?php
if(!empty($pdo_result)) {
foreach($pdo_result as $pdo_row) {
$id = $pdo_row['id'];
$name = $pdo_row['item_title'];
$img = $pdo_row['item_img'];
$price = $pdo_row['item_price'];
$sold = $pdo_row['item_sold'];
$stocks = $pdo_row['stocks'];
$date = $pdo_row['date'];
if ($sold >= $max && $date != date("Y-m-d") ) {
$sort = 'hot';
}else if($date == date("Y-m-d") && $sold <= $max){
$sort = 'new';
}else{
$sort = '';
}
echo '
<div class="product grid-item '.$sort.'">
<div class="product_inner">
<div class="product_image">
<img src="'.$img.'" alt="">
<div class="product_tag">'.$sort.'</div>
</div>
<div class="product_content text-center">
<div class="product_title text-long">'.$name.'</div>
<div class="product_price">₱'.number_format($price).'</div>
<div class="product_button ml-auto mr-auto trans_200">
<button class="product_button ml-auto mr-auto trans_200" id="add2c" data-prod=" '.$id.' " type="button" >add to cart</button>
</div>
</div>
</div>
</div>
';
} //End Foreach Loop
}
else{
echo "no products found";
}
?>
</div>
</div>
</div>
<!-- PAGINATION HERE -->
<?php echo $per_page_html; ?>
Method 1 => Without ajax
You can use the GET method for search value also. and in every pagination link
append the search value too.
for example.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
instead of above line use below one.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'&search='.$keyword.'">Next</a>';
Method 2 => using ajax
instead of href use a javascript function like below
$next_link = '<a class="paginate_next" href="#" onclick="paginate_fn(\''.$next_id.'\', \''.$keyword.'\'">Next</a>'
<script>
function paginate_fn(pageID, keyword){
$.ajax({
async: true,
type: 'get', // you can use post also
dataType:'json',
data: {'pageID':pageID, 'keyword': keyword},
url: "paget_name.php", // your page name
success: function (data) {
$('#search-content').html( data['content'] );
},
error: function () {
alert('An Error Occurred!.');
}
});
}
</script>
I'm trying to get search results to paginate if there are greater than 10 items found in the database. For some reason, even though the code recognises there are more than 10 items and creates links for subsequent pages, all search results are listed on the first page only. Anyone able to help please? Code is below:
for($i = 0; $i < $terms_count; $i++)
{
$search_terms_array[$i] = trim($search_terms_array[$i]);
${"query".$i} = $this->mysqli_link->query("SELECT prod_id, prod_tags FROM table WHERE prod_tags LIKE '%" . $search_terms_array[$i] . "%'");
if(${"query".$i}->num_rows < 1)
{
$zerocount++;
}
else
{
$rows = array();
while($row = ${"query".$i}->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
$search_id_results[] = $row['prod_id'];
}
}
}
if($zerocount == $terms_count)
{
echo $this->err_handle->fetch_error_text("search_terms_0_results");
return;
}
else
{
$search_results = array_values(array_unique($search_id_results));
$search_results_count = count($search_results);
$search_page_count = ceil($search_results_count / 10);
$search_page_first_result = ($search_page - 1) * 10;
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
for($i = 0; $i < $search_results_count; $i++)
{
$query = $this->mysqli_link->query("SELECT * FROM table WHERE prod_id='" . $search_results[$i] . "' LIMIT " . $search_page_first_result . ", 10");
while($row = $query->fetch_array())
{
echo "<h4>" . $row['prod_name'] . "</h4><p><img src=\"includes/images/product_images/" . $row['prod_category'] . "/" . $row['prod_pic_filename'] . "\" alt=\"\" width=\"150\" height=\"200\" /></p><p>Price: £" . $row['prod_price'] . "</p><p>" . $row['prod_code'] . "</p><input type=\"number\" name=\"prod_qty\" maxlength=\"2\" /><input type=\"submit\" name=\"add_to_basket\" value=\"Add To Basket\" /></form></p><p> </p><p> </p>";
}
}
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
}
Ok so I found a solution to this problem and the full function is now as follows:
public function product_search($search_terms, $search_page, $search_flag_check)
{
if($search_flag_check == "invalid")
{
echo $this->err_handle->fetch_error_text("invalid_ns_term");
return;
}
if($search_terms == "")
{
echo $this->err_handle->fetch_error_text("no_search_string");
return;
}
$search_terms = htmlspecialchars($search_terms);
$search_terms = $this->mysqli_link->real_escape_string(filter_var($search_terms, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES));
$search_terms_array = explode(" ", $search_terms);
$terms_count = count($search_terms_array);
$zerocount = 0;
$search_id_results = array();
for($i = 0; $i < $terms_count; $i++)
{
$search_terms_array[$i] = trim($search_terms_array[$i]);
${"query".$i} = $this->mysqli_link->query("SELECT prod_id, prod_tags FROM table WHERE prod_tags LIKE '%" . $search_terms_array[$i] . "%'");
if(${"query".$i}->num_rows < 1)
{
$zerocount++;
}
else
{
$rows = array();
while($row = ${"query".$i}->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
$search_id_results[] = $row['prod_id'];
}
}
}
if($zerocount == $terms_count)
{
echo $this->err_handle->fetch_error_text("search_terms_0_results");
return;
}
else
{
$search_results = array_values(array_unique($search_id_results));
$search_results_count = count($search_results);
$search_page_count = ceil($search_results_count / 10);
$search_page_first_result = ($search_page - 1) * 10;
$search_page_results_limit = 10;
if($search_page_first_result < 1)
{
$search_page_first_result = 1;
}
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
$search_page_upper_limit = $search_page_first_result + 9;
if(array_key_exists($search_page_upper_limit, $search_results))
{
$search_results_limit = $search_page_first_result + $search_page_results_limit;
}
else
{
end($search_results);
$search_results_limit = key($search_results);
reset($search_results);
}
for($i = $search_page_first_result; $i <= $search_results_limit; $i++)
{
$query2 = $this->mysqli_link->query("SELECT * FROM table WHERE prod_id='" . $search_results[$i] . "'");
$row = $query2->fetch_array();
echo "<h4>" . $row['prod_name'] . "</h4><p><img src=\"includes/images/product_images/" . $row['prod_category'] . "/" . $row['prod_pic_filename'] . "\" alt=\"\" width=\"150\" height=\"200\" /></p><p>Price: £" . $row['prod_price'] . "</p><p>" . $row['prod_code'] . "</p><input type=\"number\" name=\"prod_qty\" maxlength=\"2\" /><input type=\"submit\" name=\"add_to_basket\" value=\"Add To Basket\" /></form></p><p> </p><p> </p>";
}
echo '<p>Go to page: ';
for($i = 1; $i <= $search_page_count; $i++)
{
if($i == $search_page)
{
echo " <strong>" . $i . "</strong>";
}
else
{
echo ' ' . $i . '';
}
}
echo '</p><p> </p><p> </p>';
}
}
It took a bit of thinking and I was about to give up, but then I thought about using the array keys to calculate the limits for each search page and after a bit of googling on relevant PHP array functions it all fell into place quite well.
I understand the code may not be very tidy right now and there may be ways to optimize/improve it, however for the time being it does the job.
I'm trying to active class on list
Kindly if any one can help me to add class="active" on displayed pagination page:
$perpage= $conf['perpage'];
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
};
$start_from = ($page-1) * $perpage;
$result = "SELECT * FROM topics LIMIT $start_from, $perpage";
$result = mysql_query ($result);
$n = 0;
while ($row = mysql_fetch_array ($result)){
echo '<tr>';
echo '<td>'.$row['topic_no'].'</td>';
echo '</tr>';
++$n;
}
$sql = "SELECT * FROM topics";
$result = mysql_query($sql);
$total_records = mysql_num_rows($result);
$total_pages = ceil($total_records / $perpage);
echo '<ul class="pagination">';
echo "<li><a href='topics.php?page=1'>".'<'."</a></li> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<li ><a href='topics.php?page=".$i."'>".$i."</a></li> ";
};
echo "<li><a href='topics.php?page=$total_pages'>".'>'."</a> </li>";
echo '</ul> ';
Thanks in Advance
You Can also try this code. it's working
$c="active";
for ($i=1; $i <$total_page ; $i++) {
if($page==$i)
{
$c="active";
}
else
{
$c="";
}
echo "<li class=\"$c\">$i</li>";
}
$active = $i == $page ? 'class="active"' : '';
echo "<li ><a {$active} href=\"topics.php?page={$i}\">{$i}</a></li> ";
We just need to add class="active" only if page is current, otherwise we add nothing. If you already have classes for rows - you just need to use smth like
$activeClass = $i == $page ? 'active' : '';
echo "<li ><a class=\"my-row-class1 {$activeClass}\" href=\"topics.php?page={$i}\">{$i}</a></li> ";
echo "<li if($_GET['page']==$i){ class='active'}><a href='topics.php?page=".$i."'>".$i."</a></li> ";
Please try this. It might help you
$search = #$_GET['page']; // get value form other page
$page ='A';
for ($Page=1; $Page <27 ; $Page++) { ?> // abcdef... create
<li class="<?php if($search==$page){ echo 'active'; } ?>"> <?php echo ''. $page++ . '' ;?> </li>
<?php } ?>
/* if($search==$page){ echo 'active'; } this code means if search value == alphabet then class active call automatically */
I have a pagination class with buildTrail function to display pages number.
For searching the db, this class is working great.
If i'm searching for "intel", the second page link will be "http://localhost/search/intel/pg/2".
The problem occures when i try to filter the results .EX: "http://localhost/search/intel/type/ssd" so the links for paging will display : ex"http://localhost/search/intel/type/ssd/intel/type/ssd/pg/2"
function buildTrail($param = ""){
// $cur_page = basename($_SERVER['PHP_SELF']);
$link = $_SERVER['REQUEST_URI'];
$link_array = explode('/', $link);
//$count = count($link_array);
$pagename = $link_array[1];
// echo $magename;
if(is_array($param)){
foreach($param as $a => $b){
if($a != "page"){
$url .= $pagename."/".$b;
}
}
} else {
$url = $param;
}
$trail = "";
if($this->getPages() > 1){
if($this->getFrom() > 1){
$trail .= "<a href='" . WEBSITE . "/". $url . "/pg/" . $this->getPrevious()."'>«</a>\n ";
}
if($this->getFrom() < 10 && $this->getPages() > 10){
for ($i = 1; $i <= 10; $i++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
} elseif($this->getFrom() < 10 && $this->getPages() < 10){
for ($i = 1; $i <= $this->getPages(); $i++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
}elseif ($this->getFrom() >= 10 && $this->getFrom() <= ($this->getPages() - 5) ){
for ($i = ($this->getFrom() - 5); $i <= ($this->getFrom() + 5); $i ++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
} else {
for ($i = ($this->getPages() - 10); $i <= $this->getPages(); $i ++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
}
if($this->getFrom() < $this->getPages()){
$trail .= "<a href='" . WEBSITE . "/".$url."/pg/" . $this->getNext()."'>»</a>\n ";
}
}
return $trail;
}
Solved with htaccess
RewriteEngine On
Options -Indexes
Options +FollowSymLinks
<Files .htaccess>
deny from all
</Files>
RewriteRule ^search/(.*)/pg/([0-9]+)(/)?$ search.php?page=$2&q=$1 [NC,L]
RewriteRule ^search/(.*)/sort/(.*)/$ search.php?q=$1&sort=$2 [NC,L]
RewriteRule ^search/(.*)/sort/(.*)$ search.php?q=$1&sort=$2 [NC,L]
I've adapted a simple paginated gallery to my needs, but it doesn't work as expected: usually it puts well the first "page" og pictures then in some cases it just skip some pictures and then go to further ones, in other cases it just do not load any other page (I'm using infinitescroll)
here is the php function:
function makeGallery($path, $directory, $seo){
$dir = $path . "/" . $directory;
$handle = opendir($dir);
while ($file = readdir($handle)){
if($file == '.' OR $file == '..' or $file == 'thumbs' or $file == '.DS_Store')
continue;
else
$result_array[]=$file;
}
$filecount = count(glob("" . $dir . "*.jpg"));
closedir($handle);
array_multisort($result_array, SORT_ASC);
$rows = 3;
$cols = 8;
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page = 0;
}
$num_pics = count($result_array);
$cells = $rows * $cols;
$pages = ceil($num_pics / $cells);
$num_pages = $pages - 1;
$output = array();
$slices = array();
$push = 0;
$showpage = $page + 1;
for($k=0;$k<$pages;$k++){
array_push($slices, $push);
$push = $push + $cells;
}
for($k=0;$k<$pages;$k++){
if($page == key($slices)){
$output = array_slice($result_array, current($slices), $cells);
}
next($slices);
}
reset($output);
print '<div class="container-fluid">
<div class="row">';
print "<ul id='photoswipe' class='thumbnails'>";
for($i=0;$i<$rows;$i++){
for($j=0;$j<$cols;$j++){
if(current($output) != false){
$value = current($output);
$parts = Explode('.', $value);
$title = $parts[count($parts) - 2];
$parts = Explode('-', $title);
$title = $parts[1];
if ($title == "") $title = $value;
print "<li class='box'><a title='$title' rel='group' class='thumbnails' href='$dir/$value'><img width='$width' height='inherrit' src='$dir/thumbs/$seo-$value' /></a></li>";
next($output);
}else{
print "</ul>";
}
}
}
$ref = $_SERVER['PHP_SELF'];
if($num_pages == '0'){
print " ";
print " ";
}elseif(($page == '0')||($page == '')){
$next = $page + 1;
print " ";
print "<a id='next' href='$ref?page=$next'> </a>";
}elseif($page == $num_pages){
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print " ";
}else{
$next = $page + 1;
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print "<a id='next' href='$ref?page=$next'> </a>";
}
echo "<nav id='page-nav'>
<a href='$ref?page=$next'></a>
</nav></div></div>";
}
I'm sure there should be some silly bug that i've not spotted and i hope that some experienced php programmer can find it very easily.
you could see the gallery (and its problem) on http://eikonabox.com/page/portrait.php
(in the portrait gallery as you can see it jumps from the number 24 directly to number 49)
Thank you all
If somone get stuck in this kind of problem I've resolved this way:
function makeGallery($path, $directory, $seo){
$dir = $path . "/" . $directory;
$filearray = array();
if ($fil = opendir($dir)) {
while (($file = readdir($fil)) !== false) {
if ($file != "." && $file != ".." && $file != "thumbs" && $file != ".DS_Store") {
$filearray[] = $file;
$page = empty($_GET['page']) ? 1 : $_GET['page'];
$num_per_page = 25;
$total_pages = ceil(count($filearray)/$num_per_page);
}
}
array_multisort($filearray, SORT_ASC);
print '<div class="container-fluid">
<div class="row">';
print "<ul id='photoswipe' class='thumbnails'>";
for($i = ($page - 1) * $num_per_page; $i < $page * $num_per_page; $i++){
$value = basename($filearray[$i]);
$parts = Explode('.', $value);
$title = $parts[count($parts) - 2];
$parts = Explode('-', $title);
$title = $parts[1];
if ($title == "") $title = $value;
if($value != "")
print "<li class='box'><a title='$title' rel='group' class='thumbnails' href='$dir/$value'><img width='$width' height='inherrit' src='$dir/thumbs/$seo-$value' /></a></li>";
}
closedir($fil);
}
print "</ul>";
$ref = $_SERVER['PHP_SELF'];
if($num_pages == '0'){
print " ";
print " ";
}elseif(($page == '0')||($page == '')){
$next = $page + 1;
print " ";
print "<a id='next' href='$ref?page=$next'> </a>";
}elseif($page == $num_pages){
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print " ";
}else{
$next = $page + 1;
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print "<a id='next' href='$ref?page=$next'> </a>";
}
echo "<nav id='page-nav'>
<a href='$ref?page=$next'></a>
</nav></div></div>";
}