How to create a pagination by selecting categories? - php

I'm trying learn how to make a simple pagination.. for the first launch (index.php) it's success,
then i click the button CATEGORIES to show the products by category, it's still success..
But when i click the next page, let say page number 5, it's actually jump to the page number 5
but not in the CATEGORIES, it's back to the main page. I know it's because of this echo a href='index.php',
but i'm a beginner here, just start with php and javascript about a week ago,
so i need you "JUST CORRECT MY CODE", please don't give me a bunch of code like javascript that i'm just start to learning.
<!--index.php-->
<!doctype html>
<?php include ("functions/functions.php"); ?>
<html>
<head>
<link rel="stylesheet" href="styles/style.css" type="text/css" media="all" />
</head>
<body>
<!--NAV BUTTON-BY CATEGORY-->
<ul id="cats">
<?php getCats(); ?>
</ul>
<!--SHOWING PRODUCTS-->
<div id="wrapper">
<?php getPro(); ?> <!--FIRST LAUNCH (index.php)-->
<?php getCatPro(); ?> <!--GETTING THE PRODUCTS BY CATEGORIES-->
</div>
</body>
</html>
//functions.php
<?php
$con = mysqli_connect("localhost","root","","justLearning");
if (mysqli_connect_errno())
{
echo "The connection was not established: " . mysqli_connect_error();
}
//GETTING THE CATEGORIES (
function getCats(){
global $con;
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<li><button><a href='index.php?cat=$cat_id'>$cat_title</a></button></li>";
}
}
//FIRST LAUNCH (index.php)
function getPro(){
if(!isset($_GET['cat'])){
if(!isset($_GET['brand'])){
global $con;
$per_page=9;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$query = "SELECT * FROM products ORDER BY product_id DESC LIMIT $start_from, $per_page";
$result = mysqli_query ($con, $query);
while ($row = mysqli_fetch_array($result)){
$pro_title = $row['product_title'];
$pro_image = $row['product_image'];
echo "<div id='product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='135' height='145'/>
</div>";
}
$query = "select * from products";
$result = mysqli_query($con, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<a href='index.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='index.php?page=$total_pages'>".'Last Page'."</a>";
}
}
}
//GETTING THE PRODUCTS BY CATEGORIES
function getCatPro(){
if(isset($_GET['cat'])){
$cat_id = $_GET['cat'];
global $con;
$per_page=9;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$query = "SELECT * FROM products where product_cat='$cat_id' order by product_id DESC LIMIT $start_from, $per_page";
$result = mysqli_query ($con, $query);
while ($row_cat_pro=mysqli_fetch_array($result)){
$pro_title = $row_cat_pro['product_title'];
$pro_image = $row_cat_pro['product_image'];
echo "<div id='product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='135' height='145'/>
</div>";
}
$query = "select * from products where product_cat='$cat_id'";
$result = mysqli_query($con, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<a href='index.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='index.php?page=$total_pages'>".'Last Page'."</a>";
}
}
?>

You have to modify getCatPro() and concatenate the cat parameter to the links. For example:
echo "<a href='index.php?page=".$i."&cat=".$cat_id."'>".$i."</a> ";
Hope it helps.

Related

Pagination in PHP MySQL not limiting data and neither going to next page

I have listing in my HTML which is displayed from database. My listing code is like below:
<?php
require('admin/db_config.php');
$sql = "SELECT * FROM image_gallery";
$images = $mysqli->query($sql);
while($image = $images->fetch_assoc()){
?>
<div class="aamir"><span><img style="height:40px; width:55px; " class="img-responsive" alt="" src="admin/uploads/<?php echo $image['image'] ?>" /></span><small><?php echo $image['title']; ?></small><strong style="width:40%; height: 35%;"><em class="icon icon-chevron-down"></em><p style="margin-top: -5%;"> <?php echo $image['description']; ?> </p></strong>
<a
class="zayan" target="_blank" href="<?php echo $image['url']; ?>">VISIT</a>
</div>
<?php } ?>
Now I have given pagination for the same because the data is too much and I want it to go to next page. So I have given pagination. Pagination code is below:
<?php
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;
$conn=mysqli_connect("localhost","root","","sample");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$total_pages_sql = "SELECT COUNT(*) FROM image_gallery";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql = "SELECT * FROM image_gallery LIMIT $offset, $no_of_records_per_page";
$res_data = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($res_data)){
//here goes the data
}
mysqli_close($conn);
?>
<ul class="pagination">
<li>First</li>
<li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
Prev
</li>
<li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
Next
</li>
<li>Last</li>
</ul>
But still the pagination is not working, no error is shown, the whole data is being displayed in one page and the pagination is like static.

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();
?>

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>

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");

Sort by Price, Name script not working... PHP and MySQL

So the issue lies within the code where I try to change what the products are sorted by, the page doesnt load atm, If I comment out the _GET sort code and just change the one and only result variable to sort by e.g. price then that works, thank you!
<?php
require 'functions.php';
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<center>
<img style="position: relative; top:50px" src="logo.png"/>
</center>
<hr>
<?php cart(); ?>
<div id="shopping_cart">
<span style="float:left;">Welcome Guest | Total Items: <?php total_items();?> <b style="colour:blue;">| Total: £<?php total_price(); ?></b> Go to Cart: </span>
</div>
<div class="menu">
<ul>
<li class="select">HOME</li>
<li class="select">BASKET </li>
<li class="select">OUR WORLD </li>
</ul>
<div id="form">
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_query" placeholder="Search a Product"/>
<input type="submit" name="search" value="Search"/>
</form>
</div>
</div>
<br>
<br>
<br>
<select name="menu" id="drop">
<option>-- Select a filter --</option>
<option value="main.php?sort=name">Name A - Z</option>
<option value="main.php?sort=pasc">Price Low-High</option>
<option value="main.php?sort=pdesc">Price High-Low</option>
</select>
<script type="text/javascript">
var sortmenu = document.getElementById( 'menu' );
sortmenu.onchange = function() {
window.open( this.options[ this.selectedIndex ].value, "_self" );
};
</script>
<?php
$con = mysqli_connect(hello);
$query = "SELECT * FROM MrPiece";
#$result = mysqli_query($con, $query);
$ip=getIp();
$result = mysqli_query($con, "SELECT * FROM MrPiece ORDER BY ID ASC");
if(isset($_GET["sort"])){
if($_GET["sort"]=='pasc'){
$result = ($con,"SELECT * FROM MrPiece ORDER BY Price ASC");
}
elseif($_GET["sort"]=='pdesc'){
$result = ($con,"SELECT * FROM MrPiece ORDER BY Price DESC");
}
elseif($_GET["sort"]=='name'){
$result = ($con, "SELECT * FROM MrPiece ORDER BY Name ASC");
}
}
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$pro_id = $row['ID'];
$product_name = $row['Name'];
$product_price = $row['Price'];
$product_image = $row['Image'];
echo "<div id='products_box'>";
echo "<div id='single_product'>";
echo "<a href='details.php?pro_id=$pro_id'><img src='$product_image' style='height:250px; width:180px'></a> <br>";
echo "<a href='details.php?pro_id=$pro_id'>$product_name</a><br>";
echo "£ $product_price <br>";
echo "<a href='main.php?add_cart=$pro_id'><button style='float: center;'>Add to cart</button></a>";
echo "</div>";
echo "</div>";
}
}
else {echo "No results";}
mysqli_close($con);
?>
</body>
<html>
You've missed the mysqli_query function from inside your conditionals.
if(isset($_GET["sort"])){
if($_GET["sort"]=='pasc'){
$result = mysqli_query($con,"SELECT * FROM MrPiece ORDER BY Price ASC");
}
elseif($_GET["sort"]=='pdesc'){
$result = mysqli_query($con,"SELECT * FROM MrPiece ORDER BY Price DESC");
}
elseif($_GET["sort"]=='name'){
$result = mysqli_query($con, "SELECT * FROM MrPiece ORDER BY Name ASC");
}
}
However, this whole section could be refactored down to something like:
$query = "SELECT * FROM MrPiece ORDER BY ID ASC";
if(isset($_GET["sort"])){
if($_GET["sort"]=='pasc'){
$query = "SELECT * FROM MrPiece ORDER BY Price ASC";
}
elseif($_GET["sort"]=='pdesc'){
$query = "SELECT * FROM MrPiece ORDER BY Price DESC";
}
elseif($_GET["sort"]=='name'){
$query = "SELECT * FROM MrPiece ORDER BY Name ASC";
}
}
$result = mysqli_query($con, $query);
main.php?sort=price_asc, price_desc, name_asc etc and then exploding $_GET will leave you with the column name at array index 0 and order in array index 1 , you can then use both in your mysql/mysqli query.

Categories