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

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.

Related

How to dislpay all animals that are status = 1 in PHP

I'm making an adoption website for a project.
I'm trying to display all animals whose status = 1 but the animals whose status = 0 keeps appearing in the category.
Is something wrong with my code? suggestions and corrections are welcome.
Thank you!
function.php
function get_animals($cat_id='', $animal_id='')
{
global $con;
$query = "SELECT * FROM animals WHERE status= 1";
if($cat_id!='')
{
$query = "SELECT * FROM animals WHERE category_name='$cat_id'";
}
if ($animal_id!='')
{
$query = "SELECT * FROM animals WHERE id=$animal_id";
}
return $result = mysqli_query($con,$query);
}
This is my animals.php file
<?php
$cat_id = '';
if(isset($_GET['id']))
{
$cat_id = mysqli_real_escape_string($con,$_GET['id']);
}
$particular_animal = get_animals($cat_id);
?>
<!-- End Navigation -->
<!-- Product Grid -->
<div class="container mt-5 ">
<div class="row">
<?php
if(mysqli_num_rows($particular_animal))
{
while($row = mysqli_fetch_assoc($particular_animal))
{
?>
<div class="col-md-4 product-grid">
<div class="row">
<div class="image border border-info bg-light">
<a href="animal_details.php? a_id=<?php echo $row ['id'] ?>">
<img src="admin/image/<?php echo $row['img']?>" class="w-100" alt="">
</a>
<h4 class="text-center mt-2 text-info font-weight-bold"><?php echo $row ['name'] ?></h4>
<p class="text-center mt-2"><?php echo $row ['gender'] ?></p>
</div>
</div>
</div>
<?php
}
}
else
{
echo "record not here";
}
?>
</div>
</div>
You're overwriting your $query (the one with the status) when $cat_id or $animal_id is set. Instead, add to the WHERE clause of your first query:
$query = "SELECT * FROM animals WHERE status= 1";
if($cat_id != '') {
$query .= " AND category_name='$cat_id'";
}
if ($animal_id != '') {
$query .= " AND id=$animal_id";
}
If your function gets a category id or an animal id, then your query is overriden and your status criteria is lost. This is a 1-command solution:
function get_animals($cat_id='', $animal_id='')
{
return mysqli_query($con,"SELECT * FROM animals WHERE status= 1" .
($cat_id ? " AND category_name = {$cat_id} " : "").
($animal_id ? " AND animal_id = {$animal_id} " : ""));
}

Pagination on a server-side website is not working

It's my index.php:
<?php
$maxlinks = 4;
$paginaAtual = (isset($_GET['paginaAtual'])) ? (int)$_GET['paginaAtual'] : 1;
$maximo = 5;
$inicio = (($maximo * $paginaAtual) - $maximo);
$publicacoesUN = DBRead('publicacao', "ORDER BY id DESC LIMIT $inicio, $maximo");
$post = empty($_GET['post']) ? '' : $_GET['post'];
$pagina = empty($_GET['p']) ? 'home' : $_GET['p'];
if ($post != '' || ($post == '' && $pagina != '')) {
switch ($pagina):
case 'home':
$titulo = '';
$shareTitulo = '';
$descricao = '';
$shareDescricao = '';
$shareImg = '';
$keywords = '';
$ogUrl = '';
$urlCanonico = '';
break;
case 'ultimasnoticias':
$titulo = '';
$shareTitulo = '';
$descricao = '';
$shareDescricao = '';
$shareImg = '';
$keywords = '';
$ogUrl = '';
$urlCanonico = '';
break;
default:
$titulo = 'Home';
$pagina = 'home';
endswitch;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<nav>
<ul>
<li>
Página Inicial
</li>
<li>
Últimas Notícias
</li>
</ul>
</nav>
<?php
if (empty($post)) {
require_once 'page_' . $pagina . '.php';
} else {
require_once 'posts/' . $post . '.php';
}
?>
</body>
</html>
And my ultimasnoticias.php:
<div class="container my-3">
<div class="row">
<?php foreach ($publicacoesUN as $UN): ?>
<div class="col-12 col-md-6 col-lg-3 mb-3 mb-md-3">
<div class="card">
<div class="img-container">
<img src="<?php echo $UN['capa']?>" alt="<?php echo $UN['alt']?>" class="card-img-top" id="imgUNcover">
</div>
<div class="card-body">
<h1 class="cardTitleUN"><?php echo $UN['title']?></h1>
<p class="card-text text-muted"><?php echo $UN['text']?></p>
Continue Lendo
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=publicacoes', 'root', '');
$seleciona_2 = $pdo->prepare("SELECT * FROM `bn_publicacao`");
$seleciona_2->execute();
$total = $seleciona_2->rowCount();
$total_paginas = ceil($total/$maximo);
if($total > $maximo){
echo 'First page';
for ($i = $paginaAtual - $maxlinks; $i <= $paginaAtual -1; $i++) {
if ($i >= 1) {
echo ''.$i.'';
}
}
echo '<span>'.$paginaAtual.'</span>';
for ($i= $paginaAtual +1; $i <= $paginaAtual + $maxlinks; $i++) {
if ($i <= $total_paginas) {
echo ''.$i.'';
}
}
echo 'Last page';
}
?>
When i click on the link of the pagination like 1, 2, first page, last page...etc, it redirects to the home page. If i put the whole script from the file ultimasnoticias.php into the file index.php the pagination works.
This pagination script works for a static website, but it's not working on a server-side. How can i solve this?
I recommend you use this class! It's excellent. It does it all for you!
https://github.com/daveismyname/pagination
An example of its use (MVC format):
$pages = new Paginator('10','p');
$pages->set_total( $this->support->countAllFaq() );
$getAllFaq = $this->support->getAllFaq($pages->get_limit());
if($getAllFaq == false) { $count = 0; } else { $count = count($getAllFaq); }
$pageLinks = $pages->page_links();
The database queries:
public function countAllFaq()
{
$sql = 'SELECT f.name, f.content, f.date, f.status, f.cat_id, c.id, c.name AS catname FROM chewi_support_faq f LEFT JOIN chewi_support_categories c ON f.cat_id = c.id WHERE f.status = 1';
$results = $this->db->selectExtended($sql);
$totalRows = count($results);
if($results === FALSE){ $totalRows = '0'; }
return $totalRows;
}
public function getAllFaq($limit)
{
$sql = 'SELECT f.id, f.name, f.content, f.date, f.status, f.cat_id, c.id AS cat_id, c.name AS catname FROM chewi_support_faq f LEFT JOIN chewi_support_categories c ON f.cat_id = c.id WHERE f.status = 1 ORDER BY f.cat_id DESC '.$limit;
$results = $this->db->selectExtended($sql);
return $results;
}

Pagination not displaying proper results on second page

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>

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

display sub-menu of parent menu from parent id php

<?php
$page= $objPage-> get_page();
$id = isset($_GET['id']);
$child= $objPage-> get_child_page($id);
?>
<ul class="nav nav-tabs">
<li role="presentation" class="dropdown">
<?php
while($row = mysql_fetch_array($page) ) { ?>
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria- expanded="false">
<?php echo $row['title']; ?> <span class="caret"></span>
</a>
<?php } ?>
</li>
</ul>
Function get_page:
function get_page($id="") {
$sql = "SELECT "; if( !empty($field) ){
$sql .=" title FROM page WHERE page_id>1 " ;
} else {
$sql .= " * FROM page ";
}
if( !empty($id) ){
$sql .=" WHERE page_id=".$id;
} else {
$sql .=" WHERE parent_id= -1";
}
$result = mysql_query($sql) or die( mysql_error() );
if( !empty($id) && $result ){
$value = mysql_fetch_array($result) ;
return $value;
}
return $result;
}
Function get_child_page:
function get_child_page($id){
$sql = "SELECT * FROM page WHERE parent_id= $id";
$result = mysql_query($sql);
return $result;
}
i got the parent menu which has the parent id -1 but i want to display the child menu from parent id .. any solution ??

Categories