Pagination not displaying proper results on second page - php

I've been trying to make this work for some time now. I have a <select tag for displaying number of results on a page. Apparently, the query works on displaying all rows, but when I go to the second page, it doesn't work anymore. I've checked out a thread about using $_REQUEST variable but to no avail.
FORM
<form method="POST" action="test.php" class="navbar-form navbar-left">
<div class="form-group">
<select class="form-control" id="adNum" name="showAdsOptions" aria-describedby="categoryHelp">
<option value="10">Show 10 ads per page</option>
<option value="15">Show 15 ads per page</option>
<option value="20">Show 20 ads per page</option>
</select>
<input type="submit" name="filterAds" class="form-control" value="Go" />
</div>
</form>
TABLE
<table class="table table-bordered">
<?php
include 'admin/script/connection.php';
$limit = 5;
$counter = 1;
$me = $_SESSION['user'];
$selectSQL = "SELECT * FROM user_pending_ads WHERE User_Name='$me'";
$result = $conn->query($selectSQL);
$total = $result->num_rows;
if (isset($_GET['p']) == null) {
$p = 0;
} else {
$p = $_GET['p'];
if($p == 1) {
$p = $p-1;
} else {
$p = ($p-1) * $limit;
}
}
if ($limit > $total) {
$nop = 1;
} else {
$nop = $total/$limit;
}
$nop = ceil($nop);
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $limit";
// SEARCH QUERY
if (isset($_GET['searchAds'])) {
if (isset($_GET['q']) == null) {
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $limit";
} else {
$search = $_GET['q'];
if ($search == "") {
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $limit";
} else {
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' AND Ad_Title LIKE '%$search%' LIMIT $p, $limit";
}
}
}
// IF SHOW # ADS PER PAGE IS SET AND GO IS CLICKED
if (isset($_POST['filterAds']) == true) {
$opt = $_REQUEST['showAdsOptions'];
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $opt";
}
$getdisplay = $conn->query($display);
while ($col = $getdisplay->fetch_assoc()) {
...
}
?>
</table>
PAGINATION
<ul class="pagination">
<?php
if ($total >= 1) {
?>
<li>First</li>
<?php
for ($i = 1; $i <= $nop; $i++) {
?>
<li><?php echo $i ?></li>
<?php
}
?>
<li>Last</li>
<?php
}
?>
</ul>

Related

How to do pagination inside php file which is passed by ajax

I am trying to do pagination in my php file fetch_data.php which is called from a ajax function in index.php but it is not showing the required result
Here is my code from fetch_data.php
<?php
require 'dbserver.inc.php';
$query = "
SELECT * FROM detail WHERE status = '1'
";
$result = mysqli_query($conn,$query);
$number = mysqli_num_rows($result);
$results_per_page = 1;
$number_of_pages = ceil($number/$results_per_page);
if (!isset($_GET['page'])) {
$page = 1;
echo"1";
} else {
echo"2";
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
if(isset($_POST["action"]))
{
$query = "
SELECT * FROM detail WHERE status = '1'
AND LIMIT" . $this_page_first_result . ',' . $results_per_page ;
if(isset($_POST["jobtype"]))
{
$jobtype_filter = implode("','", $_POST["jobtype"]);
$query .= "
AND Job IN('".$jobtype_filter."')";
}
if(isset($_POST["salary"]))
{
$salary_filter = implode("','", $_POST["salary"]);
$query .= "
AND Salary IN('".$salary_filter."')";
}
if(isset($_POST["category"]))
{
if($_POST["category"] == 'Choose Category')
{
$query .= "";
}
else
{
$category = $_POST["category"];
$query .= "
AND JobCat like('".$category."')";
}}
if(isset($_POST["location"]))
{
if($_POST["location"] == 'Choose Location')
{
$query .= "";
}
else
{
$location = $_POST["location"];
$query .= "
AND City like('".$location."')";
}}
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_assoc($result)){
echo'
<!-- Single Employers List -->
<div class="candidate-list-layout" >
<div class="cll-wrap">
<div class="cll-thumb">
<a href="company-detail.html">';?>
<img class="img_responsive" alt="" src="data:image/jpg;charset=utf8;base64,<?php echo base64_encode($row['Logo']); ?>" /> <?php echo'</a>
</div>
<div class="cll-caption">
<h4>'.$row['Name'].'<span><i class="ti-briefcase"></i>'.$row['Title'].'</span></h4>
<ul>
<li><i class="ti-location-pin cl-danger"></i>'.$row['City'].' fetch ,'.$row['Country'].'</li>
<li><i class="ti-medall cl-success"></i>Established: 1984</li>
</ul>
</div>
</div>
';}
echo'<div class="row mrg-0">
<ul class="pagination">';
for($page = 1 ; $page<=$number_of_pages;$page++){
echo'
<li class="active">'.$page.'</li>
';}
echo' <li><i class="fa fa-ellipsis-h"></i></li>
</ul>
</div>';
}
?>
i want to filter the data a also due to which i have to include these other lines of codes and it is also not redirercting to other page except the one it is currently in and when included these filter code it is showing boolean error on mysqli_query too.

URL encoding the space character

Someone pls help me. I have search form and displaying data from database and im using jquery twbsPagination. So my problem is the space in url if the user search two or more words.I used encodeURIComponent(); its work perfectly fine its display data. but when i click on page 2. its display no data and when i go back to the first page the datas is not showing anymore. help me pls. im debugging for 12 hrs sorry for my english.
this is my form
<div class="input-group input-group-lg">
<input id="searchBar" type="text" class="form-control" placeholder="Search job">
<span class="input-group-btn">
<button id="searchBtn" type="button" class="btn btn-info btn-flat">Go!</button>
</span>
</div>
and this is my script
<script>
function Pagination(){
<?php
$limit=5;
$sql="SELECT COUNT(id_jobpost) AS id from job_post";
$result=$conn->query($sql);
if($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$total_records = $row['id'];
$total_pages = ceil($total_records / $limit);
} else {
$total_pages = 1;
}
?>
$('#pagination').twbsPagination({
totalPages: <?php echo $total_pages;?>,
visible: 5,
onPageClick: function(e, page){
e.preventDefault();
$(".target-content").html("Loading....");
$(".target-content").load("job-pagination.php?page="+page);
}
});
}
</script>
<script>
$(function(){
Pagination();
});
</script>
<script>
$("#searchBtn").on("click", function(e){
e.preventDefault();
var searchResult = $("#searchBar").val();
var filter = "searchBar";
if (searchResult != "") {
$('#pagination').twbsPagination('destroy');
Search(searchResult,filter);
}else{
$('#pagination').twbsPagination('destroy');
Pagination();
}
});
<script>
function Search(val,filter){
$('#pagination').twbsPagination({
totalPages: <?php echo $total_pages; ?>,
visible: 5,
onPageClick: function(e, page){
e.preventDefault();
val = encodeURIComponent(val);
$(".target-content").html("Loading....");
$(".target-content").load("search.php?page="+page+"&search="+val+"&filter="+filter);
}
});
}
</script>
and this is my search.php
<?php
session_start();
require_once("db.php");
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $limit";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while ($row=$result->fetch_assoc()) {
$sql1 = "SELECT * FROM company WHERE id_company='$row[id_companyname]'";
$result1 = $conn->query($sql1);
if($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc())
{
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row['jobtitle']; ?> <span class="attachment-heading pull-right">₱<?php echo $row['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> | <?php echo $row1['province'].",".$row1['city']; ?> | Experience Required(in years): <?php echo $row['experience']; ?></strong></div>
</div>
</div>
</div>
<?php
}
}
}
}else{
echo "<center><strong>No Job Matched!</strong></center>";
}
$conn->close();
?>
I think the error is in your search.php page code. You need to change your ending limit.
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $limit";
When you are on the first page, you are doing: LIMIT 0, 5. When you are on the second page, you are doing: LIMIT 5, 5.
I suggest:
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$end_at = $page * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $end_at";
However I also noticed that in your search page you are doing a query inside of a query, I think a better way to do this is with a join so you only hit the database once. I don't know the structure of your database but the below code is an example of a better way to go about it so that you only hit the database once:
<?php
session_start();
require_once("db.php");
$page_size = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $page_size;
$end_at = $page * $page_size;
$search = $_GET['search'];
$sql = "
SELECT
j_p.*,
c.*
FROM
job_post j_p,
company c
WHERE
jobtitle LIKE '%$search%'
and c.id_company = j_p.id_companyname
ORDER BY
id_jobpost DESC
LIMIT
$start_from,
$end_at
";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while($row1 = $result1->fetch_assoc()) {
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row1['jobtitle']; ?> <span class="attachment-heading pull-right">₱<?php echo $row1['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> | <?php echo $row1['province'].",".$row1['city']; ?> | Experience Required(in years): <?php echo $row1['experience']; ?></strong></div>
</div>
</div>
</div>
<?php
}
}else{
echo "<center><strong>No Job Matched!</strong></center>";
}
$conn->close();
?>

Delete first post and show second in PHP

I have a question in PHP.
I am creating a website with posts but I can't make the PHP to show just the second post (without show the first).
My code is like this:
<?php
$result = mysqli_query($dbc, "SELECT * FROM projects");
$x = 1;
while($row = mysqli_fetch_array($result)){
$nome = $row['name'];
$conteudo = $row['description'];
$imagem = $row['image'];
$imagem2 = $row['image2'];
?>
<?php static $count2 = 0; if ($count2 == "1") { break; } else { ?>
<div class="content justify" id="projects-<?php echo $x; ?>" >
<?php echo $conteudo; ?>
<?php if(!empty($imagem2)) { ?>
<img class="hide-for-small" src="images/contebt/project/<?php echo $image2; ?>">
<?php }; ?>
</div>
<?php $count2++; } ?>
<?php $x++;}; ?>
With this code I can show just the first post, but I want to show just the second. Can anybody help me, please? Thanks!
This should work with this code :
PHP
<?php
$result = mysqli_query($dbc, "SELECT * FROM projects");
$x = 0;
while($row = mysqli_fetch_array($result)) {
$nome = $row['name'];
$conteudo = $row['description'];
$imagem = $row['image'];
$imagem2 = $row['image2'];
if (!$x) {
$x = 1;
continue;
}
?>
<div class="content justify" id="projects-<?php echo $x; ?>" >
<?php echo $conteudo; ?>
<?php if(!empty($imagem2)) { ?>
<img class="hide-for-small" src="images/contebt/project/<?php echo $image2; ?>">
<?php } ?>
</div>
<?php
$x++;
}
?>
SQL
But you should directly espace the first row directly in mysql usign either limit :
$result = mysqli_query($dbc, "SELECT * FROM projects LIMIT 1, 1");
or where statement :
$result = mysqli_query($dbc, "SELECT * FROM projects where id > 1");

php MySQL loop within nested divs

I have a nested div in which I want to fetch data from my database. I have explained what I want below:
<div class="row-fluid">
<div class="span6">
**First Entry Here**
</div>
<div class="span6">
**Second Entry Here**
</div>
</div>
<div class="row-fluid">
<div class="span6">
**Third Entry Here**
</div>
<div class="span6">
**FourthEntry Here**
</div>
</div>
and so on...
I am literally confused right now and the solution is not clicking in my mind. I have this code so far:
$sql = "SELECT * FROM `users`";
$result = mysqli_query($conn, $sql);
$ic = 0;
while ($row = mysqli_fetch_assoc($result)) {
if(($ic%2) == 0) {
$div1 = '<div class="row-fluid">';
$div2 = '</div>';
}else{
$div1 = '';
$div2 = '';
}
?>
<?=$div1;?>
<div class="span6">
<?=$row['userid'];?>
</div>
<?=$div2;?>
<?php
$ic = $ic + 1;
}
?>
I have tried two while loops but it was outputting around 5000 lines of code.
$ic = 0;
$temp = "";
while ($row = mysqli_fetch_assoc($result)) {
$temp .= "<div class='span6'>".$row['user_id']."</div>";
if ( $ic % 2 != 0 ){
echo "<div class='row-fluid'>".$temp."<div>";
$temp = "";
}
$ic++;
}
// in case the number of records are odd::
if ($temp != "" )
echo "<div class='row-fluid'>".$temp."<div>";
#Amr Magdy logic is correct, however the solution didn't work out for me. I have now managed to fix it and if anyone else has the same situation may refer to the code below:
<?php
$sql = "SELECT * FROM `users`";
$result = mysqli_query($conn, $sql);
$ic = 0;
$temp = "";
while ($row = mysqli_fetch_assoc($result)) {
$temp = '<div class="span6">'.$row['userid'].'</div>';
if(($ic%2) == 0) {
echo '<div class="row-fluid">'.$temp;
$temp = "";
}else{
echo $temp;
}
$ic = $ic + 1;
}
echo '</div>';
?>

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;
}

Categories