How to paginate search result using php pdo? - php

I am creating a pagination for search result all looks fine on first loading page,
but when I click on paginated links then it show me a white page (search page but without entries in).
simply with no results found from my data
This is the site search box in index.php
<form action="search/" method="post">
<input type="text" name="search" placeholder="word..." required />
<input type="submit" name="submit_search" class="search-btn" value="" />
</form>
Here is my setup for htaccess pagination:
RewriteRule ^search/page/(.*)$ search.php?page=$1 [L,NC]
it looks fine on browser.
Here is my search page codes:
<?php
if(isset($_POST['submit_search']) && !empty($search)){
$search = htmlspecialchars(strip_tags($_POST['search']), ENT_QUOTES);
$perpage = intval("12");
$n_stmt = $pdo->prepare("SELECT * FROM posts");
$n_stmt->execute();
$total_posts = $n_stmt->rowCount();
$total_pages = ceil($total_posts/$perpage);
$page = !empty($_GET['page']) && intval($_GET['page']) ? (int) intval($_GET['page']) : intval("1");
if($page < intval("1")) $page = intval("1");
if($page > $total_pages) $page = $total_pages;
$limit = ($page - intval("1")) * $perpage;
$pages_to_show = intval("10");
$stmt = $pdo->prepare("SELECT * FROM posts WHERE title LIKE :search OR subject LIKE :search OR descriptions LIKE :search OR keywords LIKE :search ORDER BY created DESC LIMIT :limit, :perpage");
$stmt->bindValue(":search","%".$search."%", PDO::PARAM_STR);
$stmt->bindValue(":limit",$limit, PDO::PARAM_INT);
$stmt->bindValue(":perpage",$perpage, PDO::PARAM_INT);
if($stmt->execute()){
if($stmt->rowCount() > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){?>
<div class="news_box">
<a href="<?php echo htmlspecialchars($row['news_url']);?>/" title="<?php echo htmlspecialchars($row['title']);?>">
<div class="title"><h2><?php echo htmlspecialchars($row['title']);?></h2></div>
<div class="image">
<img src="images/posts/<?php echo htmlspecialchars($row['img']);?>" alt="<?php echo htmlspecialchars($row['title']);?>"/></div>
<div class="spot"><?php echo htmlspecialchars($row['subject']);?></div>
</a>
</div>
<?php
}
}
}
unset($stmt);
?>
Here is my pagination part:
<div class="pagination">
<?php if($page >1){?>
First
previous
<?php } for($i = $page - $pages_to_show; $i < $page + $pages_to_show + 1; $i++){
if($i > 0 and $i <= $total_pages){
if($i == $page){?>
<?php echo intval($i);?>
<?php }else{?>
<?php echo $i;?>
<?php
}
}
?>
<?php } ?>
<?php if($page != $total_pages){?>
Next
Last
<?php } ?>
</div>

Related

Product Refine filter by categories, price and regions

I am still learning web development and I am working on a project in order to learn how to develop a complete website with all functionalities. I am currently trying to implement the product refine filter by categories, condition, region and price. I started doing the filter according to categories and regions only, to see how I could go about but my attempt to do it failed. Whenever I check a box, itfetches the categoryId in the url but gives me an error about sql syntax.
The error message received:
I have 4 tables
ads table with adId, title, catId, regionId, price, condition, description
category table with catId, catName
region table with regionId, regionName
images table with imageId,adId,path, preview
Can anyone help me to find a solution to my problem?
Here is my class file
public function getAllCat(){
$query = "SELECT * FROM category ORDER BY catId";
$result = $this->db->select($query);
return $result;
}
public function getAllRegion(){
$query = "SELECT * FROM region ORDER BY regionId";
$result = $this->db->select($query);
return $result;
}
public function getAllAds(){
$query = "SELECT * FROM ads ORDER BY adId DESC";
$result = $this->db->select($query);
return $result;
}
public function getPreviewImage($id){
$query = "SELECT * FROM images WHERE adId = $id AND preview = '1' ";
$image = $this->db->select($query);
return $image;
}
Here is my allads.php file
<?php
//declaration array varible
$filtercategory = array();
$filterregion = array();
//finding query string value
if(isset($_REQUEST['filtercategory'])){
//query string value to array and removing empty index of array
$filtercategory = array_filter(explode("-",$_REQUEST['filtercategory']));
}
if(isset($_REQUEST['filterregion'])){
$filterregion = array_filter(explode("-",$_REQUEST['filterregion']));
}
?>
<main class="cd-main-content">
<div class="Ads-Container">
<?php
//Pagination start
$query = "SELECT COUNT(adId) FROM ads";
$result = $db->select($query);
$row = mysqli_fetch_row($result);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 20;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
?>
<?php
$query = "SELECT * FROM ads ORDER BY adId DESC $limit";
//filter query start
if(!empty($filtercategory)){
$categorydata =implode("','",$filtercategory);
$query .= " and catId in('$categorydata')";
}
if(!empty($filterregion)){
$regiondata =implode("','",$filterregion);
$query .= " and regionId in('$regiondata')";
}
//filter query end
$post = $db->select($query);
if($post){
while($result = $post->fetch_assoc()){
?>
<div class="ads-column_2">
<div class="ads-column-thumbnail">
<?php
$preview = $ad->getPreviewImage($result["adId"]);
if($preview){
while($rresult = $preview->fetch_assoc()){
?>
<img src="/afro-circle/<?php echo $rresult['path']?>" alt="" class="image-responsive">
<?php } } ?>
<div class="ads-preview-details">
<center>
<h4><?php echo $result['title']; ?></h4>
<h4 class="">FCFA <?php echo number_format($result['price']); ?></h4>
</center>
</div>
<div class="space-ten"></div>
<div class="btn-ground text-center">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#product_view">Quick View</button>
</div>
<div class="space-ten"></div>
</div>
</div>
<?php } } ?>
</div>
<!-- /.row -->
<div class="row" style="text-align: center;">
<?php
// This shows the user what page they are on, and the total number of pages
$textline1 = "Testimonials (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'First Page ';
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= '<span>'.$pagenum.'</span> ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
$paginationCtrls .= ' Last Page ';
}
}
?>
<div class="pagination">
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</div>
<!-- /.row -->
<div class="cd-filter filter-is-visible">
<form>
<div class="cd-filter-block">
<h4>Categories <span class="spanbrandcls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<ul class="cd-filter-content cd-filters list">
<?php
$getCategory = $category->getAllCat();
if($getCategory){
while($result = $getCategory->fetch_assoc()){
?>
<li>
<input type="checkbox" class="filter filtercategory" value="<?php echo $result['catId']; ?>" <?php if(in_array($result['catName'],$filtercategory)){ echo"checked"; } ?> >
<label class="checkbox-label" id="Category" ><?php echo $result['catName']; ?></label>
</li>
<?php } } ?>
</ul> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Size <span class="spansizecls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<div class="cd-filter-content">
<div class="cd-select cd-filters">
<select class="filter scheck" name="subcatId">
<option data-type="sizes" value="">Item Condition</option>
<option data-type="sizes" value="1">New</option>
<option data-type="sizes" value="2">Used</option>
</select>
</div> <!-- cd-select -->
</div> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Region <span class="spancolorcls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<ul class="cd-filter-content cd-filters list">
<?php
$getRegion = $region->getAllRegion();
if($getRegion){
while($result = $getRegion->fetch_assoc()){
?>
<li>
<input type="radio" class="filter filterregion" value="<?php echo $result['regionId']; ?>" <?php if(in_array($result['regionName'],$filterregion)){ echo"checked"; } ?>>
<label class="radio-label" for="radio1"><?php echo $result['regionName']; ?></label>
</li>
<?php } } ?>
</ul> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
</form>
<i class="fa fa-close"></i> Close
</div>
<i class="fa fa-filter"></i> Search by:
<div class="clear"></div>
Here is my JS
<script>
$(function(){
$('.filter').click(function(){
var filtercategory = multiple_values('filtercategory');
var filterregion = multiple_values('filterregion');
var url ="allads.php?filtercategory="+filtercategory+"&filterregion="+filterregion;
window.location=url;
});
});
function multiple_values(inputclass){
var val = new Array();
$("."+inputclass+":checked").each(function() {
val.push($(this).val());
});
return val.join('-');
}
The problem lies in the following section of the code:
$query = "SELECT * FROM ads ORDER BY adId DESC $limit";
//filter query start
if(!empty($filtercategory)){
$categorydata =implode("','",$filtercategory);
$query .= " and catId in('$categorydata')";
}
if(!empty($filterregion)){
$regiondata =implode("','",$filterregion);
$query .= " and regionId in('$regiondata')";
}
The code insert the filter criteria at the en of the sql statement, which means after the limit. So, the actual sql statement looks something like as follows:
SELECT * FROM ads ORDER BY adId DESC LIMIT 10, 10 and catId in('4')
The correct sql code would look something like:
SELECT * FROM ads WHERE catId in('4') ORDER BY adId DESC LIMIT 10, 10
You must modify your php code to generate valid sql code. While debugging, add code that prints out the full sql statement to see the full sql ststement before it is executed.
Also, your code is wide open to sql injection attacks. Pls use prepared statements or other techniques to prevent such attacks.

Search PHP/MySQL with Pagination

I wrote this code to search in rows of the table:
<div class="container mx-auto">
<!--Add class table-responsive for responsive table -->
<div class="row">
<div class="col-md-6">
<form method="post">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search for..." name="searchValue">
<span class="input-group-btn">
<button class="btn btn-secondary" name='search' type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</div>
</div>
<table class="table mx-auto" id="'table">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>Phone</th>
<th>Company</th>
<th>More</th>
</tr>
</thead>
<tbody>
<?php
$page_max = 8;
if (isset($_POST['search'])){
$search = $_POST['searchValue'];
$entriesInDatabase = $database->getData("SELECT count(id) FROM customers WHERE name LIKE '%$search%'");
$numberOfPages = ceil($entriesInDatabase['count(id)']/$page_max);
$numberOfRecords = $page_max;
if(isset($_GET['page'])) {
$page = $_GET['page'];
$start = $page * $page_max;
}
else{
$page = 0;
$start = $page * $page_max;
}
$customers = $database->getUsers("SELECT * FROM customers WHERE name LIKE '%$search%' LIMIT $start, $numberOfRecords");
}
else{
$entriesInDatabase = $database->getData("SELECT count(id) FROM customers");
$numberOfPages = ceil($entriesInDatabase['count(id)']/$page_max);
$numberOfRecords = $page_max;
if(isset($_GET['page'])) {
$page = $_GET['page'];
$start = $page * $page_max;
}
else{
$page = 0;
$start = $page * $page_max;
}
$customers = $database->getUsers("SELECT * FROM customers LIMIT $start, $numberOfRecords");
}
foreach($customers as $customer){
$name = $customer ['name'];
$surname = $customer['surname'];
$email = $customer['email'];
$phone = $customer['phone'];
$company = $customer['company'];
$id = $customer['id'];
echo "<tr>
<td>$name</td>
<td>$surname</td>
<td>$email</td>
<td>$phone</td>
<td>$company</td>
<td><a href='customerInfo.php?id=$id' class='btn btn-sm btn-info'><i class='fa fa-info'></i></a></td>
</tr>";
}
?>
</tbody>
</table>
<ul class="pagination">
<?php
if(isset($_GET['page']) && $_GET['page'] > 0){
$previous = $_GET['page'] - 1;
echo '<li class="page-item"><a class="page-link" href="?page='. $previous.'">Previous</a></li>';
}
for($i = 0; $i < $numberOfPages; $i++){
echo '<li class="page-item"><a class="page-link" href="?page='. $i . '">'. $i. '</a></li>';
}
if(isset($_GET['page']) && $_GET['page'] < $numberOfPages - 1){
$page = $_GET['page'];
$next = $page + 1;
echo '<li class="page-item"><a class="page-link" href="?page='.$next.'">Next</a></li> ';
}
elseif(!isset($_GET['page'])){
echo '<li class="page-item"><a class="page-link" href="?page=1">Next</a></li> ';
}
?>
</ul>
</div>
Searching works fine when I'm on page 0, but when I'm at page 2 I can only search for records on that page (I think this is because of the limit in my query) besides that when I search for 'A' it returns 7 pages but if I click on the seconde page it won't load the search results but the main list with customers on page 2.
Could anyone help me fix these issues?
First of all: sanitize your input. Using POST or GET in database queries can be very, very dangerous.
Second: DRY, you probably can do this with half the code you are using.
The reason why you are "losing" your search is because your pagination doesn't carry over the search term.
Add it to the links in the pagination and switch from POST to GET:
<?php
$searchString = '';
if($_GET['searchValue']){
$searchString = '&searchValue=' . $_GET['searchValue'];
}
if(isset($_GET['page']) && $_GET['page'] > 0){
$previous = $_GET['page'] - 1;
echo '<li class="page-item"><a class="page-link" href="?page='. $previous.$searchString.'">Previous</a></li>';
}
// more code
'... href="?page='.$i.$searchString'" ...'
'... href="?page='.$next.$searchString'" ...'
Note that I use $_GET['searchValue'] instead of POST. in most cases there is no advantage in using POST for searches (quite the opposite, if you use GET you can track it in Google Analytics f.ex.). So make sure you change your form method to get and if (isset($_POST['search'])){ to $_GET['searchValue']. If you insist on using POST, you can use $_REQUEST, which holds values from GET and POST.

How to release pagination in "GET" search?

I use this code For search in database:
<?php
if(isset($_GET['keywords'])) {
$keywords = $CONNECT->escape_string($_GET['keywords']);
if(!$keywords){
echo("<script>location.href = '/news';</script>");
//if javascript disabled
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
?>
<div class="found">founded<?php echo $Query->num_rows; ?> </div>
</div>
</div>
<div class="ncontent">
<div class="keyword">phrase: "<p><?php echo htmlspecialchars($keywords); ?></p>"</div>
<?php
if($Query->num_rows){
while ($r = $Query->fetch_object()){
?>
<div class="nline"><a href="/news/content/id/<?php echo $r->id; ?>"><div class="prewnews">
<div class="imgh1"><img src="<?php echo $r->himg; ?>"/></div>
<span><i class="fa fa-heart-o" aria-hidden="true"> <p>124</p></i><hr style="background:#cd4436; border:0; height:3px" /><i class="fa fa-eye" aria-hidden="true"> <p><?php echo $r->readed; ?></p></i> </span>
<h3><?php echo $r->title; ?></h3>
</div>
</a>
</div>
<?php
}
}else echo '<div class="notfound"><img src="/resource/img/notfound.png" alt=""></div>';
}else {echo("<script>location.href = '/news';</script>");
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
?>
Search form:
<form action="/search" method="GET">
<input class="search red" placeholder="search..." type="search" name="keywords" autocomplete="off">
</form>
So, after search i get link like this: /search?keywords=test+search+phrase
As I think i can do like this: /search?keywords=test+search+phrase&page2
or like this: /page2/search?keywords=test+search+phrase
What you advise, which way pagination?
And can you provide links that will help to realize them?
Or anyone of you can help me here?
The following pagination solution will show at most 10 search results per page, and for navigating rest of the search results, use pagination links. The solution will show at most 5 links per page, kind of like this:
// user is on 1st page
1 2 3 4 5 ...
-
// user is on 7th page
... 5 6 7 8 9 ...
-
// user is on 10th page(lets say, 10th page is the last page)
... 6 7 8 9 10
-
So, to implement this pagination functionality, you need to make few changes in your code. Keep your HTML search form as it is, and change your PHP code in the following way,
First check if there's any ...&page=123 exists or not in the URL, and based on that, process your $_GET superglobal like this way,
if(isset($_GET['page']) && !empty($_GET['page']) && is_numeric($_GET['page'])){
$current_page = $_GET['page'];
}else{
$current_page = 1;
}
Define rows per page and calculate offset based on that, like this:
$per_page = 10; // rows per page
$offset = ($current_page - 1) * $per_page; // offset
And fetch table results based on these $per_page and $offset values, like this:
$Query = mysqli_query($CONNECT, "SELECT ... WHERE `content` LIKE ... LIMIT ". $per_page . " OFFSET " . $offset);
Now to display pagination links below the search results, follow the below procedure:
Get total number of rows from the queried result set and calculate total number of page/pagination links to display, like this:
// display pagination links
$Query = mysqli_query($CONNECT, "SELECT ... FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
if($Query->num_rows){
$total_records = $Query->num_rows;
$total_pages = ceil($total_records / $per_page);
...
Find the superset range of pages, like 1-10, or 1-20 etc. For example, if $total_pages = 20 then this superset range would be 1-20. The code for this step is this:
// superset range of pages
$superset_range = range(1, $total_pages);
Find the subset range of pages to display, like 1-5, or 3-7 etc. For example, if $total_pages = 20 then this subset range would be 1-5, or 3-7, or 6-10 etc., it can be any consecutive five pages between 1 and 20. Also, adjust this range whenever necessary. The code for this step is this:
// subset range of pages to display
$subset_range = range($current_page - 2, $current_page + 2);
// adjust the range(if required)
foreach($subset_range as $p){
if($p < 1){
array_shift($subset_range);
if(in_array($subset_range[count($subset_range) - 1] + 1, $superset_range)){
$subset_range[] = $subset_range[count($subset_range) - 1] + 1;
}
}elseif($p > $total_pages){
array_pop($subset_range);
if(in_array($subset_range[0] - 1, $superset_range)){
array_unshift($subset_range, $subset_range[0] - 1);
}
}
}
Finally, display the pagination links and dots accordingly. The code for this step is this:
// display intermediate pagination links
if($subset_range[0] > $superset_range[0]){
echo "... ";
}
foreach($subset_range as $p){
if($p == $current_page){
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "' style='text-decoration: underline;'>$p</a>";
}else{
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "'>$p</a>";
}
}
if($subset_range[count($subset_range) - 1] < $superset_range[count($superset_range) - 1]){
echo " ... ";
}
Here's the complete code:
<?php
if(isset($_GET['keywords'])) {
$keywords = $CONNECT->escape_string($_GET['keywords']);
if(!$keywords){
echo("<script>location.href = '/news';</script>");
//if javascript disabled
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
if(isset($_GET['page']) && !empty($_GET['page']) && is_numeric($_GET['page'])){
$current_page = $_GET['page'];
}else{
$current_page = 1;
}
$per_page = 10;
$offset = ($current_page - 1) * $per_page;
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%' LIMIT ". $per_page . " OFFSET " . $offset);
?>
<div class="found">founded<?php echo $Query->num_rows; ?> </div>
</div>
</div>
<div class="ncontent">
<div class="keyword">phrase: "<p><?php echo htmlspecialchars($keywords); ?></p>"</div>
<?php
if($Query->num_rows){
while ($r = $Query->fetch_object()){
?>
<div class="nline">
<a href="/news/content/id/<?php echo $r->id; ?>">
<div class="prewnews">
<div class="imgh1">
<img src="<?php echo $r->himg; ?>"/>
</div>
<span>
<i class="fa fa-heart-o" aria-hidden="true">
<p>124</p>
</i>
<hr style="background:#cd4436; border:0; height:3px" />
<i class="fa fa-eye" aria-hidden="true">
<p><?php echo $r->readed; ?></p>
</i>
</span>
<h3><?php echo $r->title; ?></h3>
</div>
</a>
</div>
<?php
}
// display pagination links
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
if($Query->num_rows){
$total_records = $Query->num_rows;
$total_pages = ceil($total_records / $per_page);
if($total_records > $per_page){
echo "<center>";
// Superset range of pages
$superset_range = range(1, $total_pages);
// subset range of pages to display
$subset_range = range($current_page - 2, $current_page + 2);
// adjust the range(if required)
foreach($subset_range as $p){
if($p < 1){
array_shift($subset_range);
if(in_array($subset_range[count($subset_range) - 1] + 1, $superset_range)){
$subset_range[] = $subset_range[count($subset_range) - 1] + 1;
}
}elseif($p > $total_pages){
array_pop($subset_range);
if(in_array($subset_range[0] - 1, $superset_range)){
array_unshift($subset_range, $subset_range[0] - 1);
}
}
}
// display intermediate pagination links
if($subset_range[0] > $superset_range[0]){
echo "... ";
}
foreach($subset_range as $p){
if($p == $current_page){
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "' style='text-decoration: underline;'>$p</a>";
}else{
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "'>$p</a>";
}
}
if($subset_range[count($subset_range) - 1] < $superset_range[count($superset_range) - 1]){
echo " ... ";
}
echo "</center> ";
}
}
}else{
echo '<div class="notfound"><img src="/resource/img/notfound.png" alt=""></div>';
}
}else {
echo("<script>location.href = '/news';</script>");
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>

Best method to add pagination to a gallery

I have clients website that is getting overloaded with images in his gallery. I was wondering if I could get some advice and see what you guys/girls think would be the best way to handle this current situation I'm in.
http://www.richsdockcompany.com/Gallery.php
This gallery is created by php and mysql. I would like to set a limit to 12 images then it would switch to a different page(s), but it can't refresh the page or else the gallery will reset.
Current Code For Gallery
<?php
include_once "header.php";
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$images = mysql_query("SELECT * FROM images");
while ($image=mysql_fetch_assoc($images))
?>
<div id="Wrap">
<div class="Titles"><h2 style="font-size:36px;">Rich's Dock Company Image Gallery</h2></div><br />
<hr />
<div id="PhotoBoxWrap">
<!--======START GALLERY======-->
<div class="row">
<div class="column grid_12">
<div class="row">
<div class="column grid_12">
<!-- start Filter categories -->
<ul id="filter">
<li class="active">All</li>
<li>Dock Builders On Shore</li>
<li>Commercial Docks</li>
<li>Residential Docks</li>
<li>Dock Repairs & Additions</li>
<li>Barge Life</li>
</ul>
<!-- End Filter categories -->
</div>
</div>
<!-- Divider -->
<div class="row">
<div class="column grid_12">
<div class="clear"></div>
<div class="divider spacer5"></div>
</div>
</div>
<!-- End divider -->
<div class="row">
<ul id="stage" class="portfolio-4column">
<?php
$images = mysql_query("SELECT * FROM images ORDER BY id DESC");
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>" data-type="<?=$image["data_type"] ?>">
<div class="column grid_3 gallerybox">
<a class="fancybox" rel="<?=$image["data_type"] ?>" href="images/gallery/<?=$image["file_name"] ?>" title="<?=$image["title"] ?>">
<img src="images/gallery/<?=$image["file_name"] ?>" alt="<?=$image["title"] ?>" class="max-img-border"></a>
<h4 style="color:#2B368D; text-align:center;"><?=$image["title"] ?></h4>
<p style="text-align:center; font-size:15px;"><?=$image["description"] ?></p>
</div>
</li>
<?php
}
?>
</ul><!--END LIST-->
The only thing I can think of off the top of my head would be to create a slider that would contain all the images or use ajax with pagination so there would be no refresh problem.
I have never attempted pagination so please go easy on me here.
Any advice would be appreciated.
Thanks!
look at this example code, which handles the pagination in a simple way.
You can reuse the function getPagesNavi for every list which should be paginated.
It returns the html with the links to navigate through the pages.
If you like to load the pages with ajax you need to do some modifications by yourself. This is only an example to show you how it could work.
$page = intval($_GET['page']);
$myurl = 'index.php?action=list';
$db->select("select * from tablename");
$count_total = $db->getRecords();
$items_per_page = 10;
$start = $page * $items_per_page;
$limit = "limit $start, $items_per_page";
$db->select("select * from tablename $limit");
while($row = $db->fetchArray()) {
// your output here...
}
echo getPageNavi($myurl,$page,$count_total,$items_per_page);
function getPagesNavi($link, $current_page, $count_total, $items_per_page, $number_of_visible_pagelinks_updown = 5, $page_varname = "page") {
$result = "";
if ($count_total <= 0) {
return "";
}
$pages_float = $count_total / $items_per_page;
$number_of_pages = ceil($pages_float) - 1;
$start = $current_page - $number_of_visible_pagelinks_updown;
$end = $current_page + $number_of_visible_pagelinks_updown;
if ($end > $number_of_pages) {
$dif = -$number_of_pages + $end;
$end = $number_of_pages;
$start = $start - $dif;
}
if ($start < 0) {
$dif = -$start;
$end = $end + $dif;
$start = 0;
}
if ($end > $number_of_pages) {
$end = $number_of_pages;
}
$back = $current_page - 1;
$forward = $current_page + 1;
if ($current_page > 0) {
$result .= "
<span class=\"pageItem\"><<</span>
<span class=\"pageItem\"><</span>";
} else {
$result .= "<span class=\"pageItem\"><<</span>";
$result .= "<span class=\"pageItem\"><</span>";
}
for ($i = floor($start); $i <= floor($end); $i++) {
$j = $i + 1;
$class = "";
if ($i == $current_page) {
$class = " currentPageItem";
}
$result.= "<span class=\"pageItem$class\">$j</span>";
}
if ($current_page != $number_of_pages) {
$result .= "<span class=\"pageItem\">></span>";
$result .= "<span class=\"pageItem\">>></span>";
} else {
$result .= "<span class=\"pageItem\">></span>";
$result .= "<span class=\"pageItem\">>></span>";
}
return $result;
}

PHP pagination does not recognize $page

I have downloaded the pagination code and used it for my website running on my local machine. After modifying and testing, there was a problem where it does not recognize the variable $page.
Please refer to the following code:
<?php
$rpp = 3; // results per page
$adjacents = 4;
$page = intval($_GET["page"]);
if($page<=0) $page = 1;
$reload = $_SERVER['PHP_SELF'];
$sql = "SELECT * FROM ".TABLE_IMAGE." ORDER BY id ASC";
$qry = mysql_query($sql, $con);
// count total number of appropriate listings:
$tcount = mysql_num_rows($qry);
// count number of pages:
$tpages = ($tcount) ? ceil($tcount/$rpp) : 1; // total pages, last page number
$i = 1;
$count = 0;
$j = ($page-1)*$rpp;
while(($result = mysql_fetch_array($qry)) && (($count<$rpp) && ($j<$tcount))){
$id = $result['id'];
$img = $result['path'];
$title = $result['title'];
$detail = $result['detail'];
$priority = $result['priority'];
$active = $result['isActive'];
?>
<div id="block-image-slider" class="<?php echo(($i%2==0)?'even':'odd')?>">
<h2><?php echo $title ?></h2><span class="operation">[កែប្រែ|លុប]</span>
<div class="block-slider-image-body">
<div class="left">
<ul>
<li>លេខរៀងទី<span class="space"><?php echo $id ?></span></li>
<li>កំនត់អទិភាពទី<span class="space"><?php echo $priority ?></span></li>
<li>ត្រូវបានបង្ហាញអោយឃើញ<span class="space"><?php echo (($active==1)?'បង្ហាញ':'មិនបង្ហាញ')?></span></li>
<li>អត្ថបទពេញ<div class="detail"><?php echo $detail ?></div></li>
</ul>
</div>
<div class="right">
<img src="<?php echo '../../image/Slider/'.$img ?>" alt="<?php echo $title ?>" width="170" height="100" />
</div>
<div style="clear:both;"></div>
</div>
</div>
<?php
mysql_data_seek($qry,$j);
$i++;
$j++;
$count++;
}//end of while loop
include("../include/paginate.php");
echo paginate_three($reload, $page, $tpages, $adjacents);
?>
This is the error it generated:
Notice: Undefined index: page in C:\wamp\www\1. Chirst Joy Church Website\common\admin\index.php on line 87
How can I fix this error?
This won't work unless your URL ends with ?page=3 (where 3 would be the current page number). In order to fix it you should change this line
$page = intval($_GET["page"]);
to
$page = (!empty($_GET["page"]) ? intval($_GET["page"]) : 1);

Categories