ORDER function with PAGINATION together. PHP/MySQLi - php
This is my order list sortOrder.php:
<?php
$queryMain ="SELECT newsvid.id, newsvid.addName, newsvid.vidTitle, newsvid.vidType, newsvid.size, newsvid.url, newsvid.vidSD, newsvid.published, videoinformation.vidLD, videoinformation.vidYear, videoinformation.vidCity, videoinformation.vidZanr, videoinformation.vidZanr2, videoinformation.vidZanr3, videoinformation.vidQuality, videoinformation.vidTranslated, videoinformation.vidTime FROM newsvid, videoinformation WHERE newsvid.id = videoinformation.id AND approved='1'";
// Video type
$vType = isset($_GET['vType']) ? $_GET['vType'] : 'ALL';
$goodTypeParam = array("AnyType", "Film", "Serials", "Cartoon", "Anime");
if (in_array($vType, $goodTypeParam)) {
if($vType == 'AnyType'){}
else{$queryMain .= " AND newsvid.vidType ='".$_GET['vType']."'";}
}
//Video Genre one
$vGenre = isset($_GET['vGenre']) ? $_GET['vGenre'] : 'ALL';
$goodGenreParam = array("AnyGenre1", "Action", "Adventure", "Comedy", "Crime", "Faction", "Fantasy", "Historical", "Horror", "Mystery", "Paranoid", "Philosophical", "Political", "Realistic", "Romance", "Saga", "Satire", "Science-Fiction", "Slice-Of-Life", "Speculative", "Anime");
if (in_array($vGenre, $goodGenreParam)) {
if($vGenre == 'AnyGenre1'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre']."')";}
}
//Video Genre two
$vGenre2 = isset($_GET['vGenre2']) ? $_GET['vGenre2'] : 'ALL';
$goodGenre2Param = array("AnyGenre2", "Action2", "Adventure2", "Comedy2", "Crime2", "Faction2", "Fantasy2", "Historical2", "Horror2", "Mystery2", "Paranoid2", "Philosophical2", "Political2", "Realistic2", "Romance2", "Saga2", "Satire2", "Science-Fiction2", "Slice-Of-Life2", "Speculative2", "Anime2");
if (in_array(vGenre2, $goodGenre2Param)) {
if(vGenre2 == 'AnyGenre2'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre2']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre2']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre2']."')";}
}
//Video Genre three
$vGenre3 = isset($_GET['vGenre3']) ? $_GET['vGenre3'] : 'ALL';
$goodGenre3Param = array("AnyGenre3", "Action", "Adventure", "Comedy", "Crime", "Faction", "Fantasy", "Historical", "Horror", "Mystery", "Paranoid", "Philosophical", "Political", "Realistic", "Romance", "Saga", "Satire", "Science-Fiction", "Slice-Of-Life", "Speculative", "Anime");
if (in_array($vGenre, $goodGenre3Param)) {
if($vGenre3 == 'AnyGenre3'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre3']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre3']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre3']."')";}
}
// Video Years
$vYear = isset($_GET['vYear']) ? $_GET['vYear'] : 'ALL';
$goodYearParam = array("AnyYear", "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", "1998", "1997");
if (in_array($vType, $goodYearParam)) {
if($vYear == 'AnyYear'){}
else{$queryMain .= " AND newsvid.vidYear ='".$_GET['vYear']."'";}
}
// Video City
$vCity = isset($_GET['vCity']) ? $_GET['vCity'] : 'ALL';
$goodCityParam = array("AnyCity", "Russian", "England");
if (in_array($vCity, $goodCityParam)) {
if($vCity == 'AnyCity'){}
else{$queryMain .= " AND newsvid.vidCity ='".$_GET['vCity']."'";}
}
//NEW of OLD
$order = isset($_GET['order']) ? $_GET['order'] : 'ALL';
$goodParam = array("NEW", "OLD");
if (in_array($order, $goodParam)) {
if($order == 'NEW'){
$queryMain .= " ORDER BY newsvid.id ASC";
}else if($order == 'OLD'){
$queryMain .= " ORDER BY newsvid.id DESC";
}else{
$queryMain .= " AND videoinformation.vidYear = 2014";
}
}
?>
And this is main page view.php:
<!DOCTYPE lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<?php include 'BSH.php' ?>
<link rel="stylesheet" type="text/css" href="CSS/sdvid.css">
<title><?php echo $lang['PAGE_TITLE_MAIN'] ?></title>
</head>
<body>
<?php
include_once 'userPages/check_login_status.php';
include_once 'incIndex/headerTop.php';
include 'connect/con.php';
include_once 'inc/sortOrder.php';
?>
<?php
$sqlPages = "SELECT COUNT(id) FROM newsvid WHERE approved='1'";
$queryPages = mysqli_query($con, $sqlPages);
$row = mysqli_fetch_row($queryPages);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 1;
// 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;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$queryMainList = $queryMain . $limit;
$resultDisplay = mysqli_query($con, $queryMainList);
// This shows the user what page they are on, and the total number of pages
$pagesTitle = "On website <b>$rows</b>";
$pagesOutOf = "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 .= '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 .= ''.$pagenum.' ';
// 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 ';
}
}
$list = '';
while($row = mysqli_fetch_array($resultDisplay, MYSQLI_ASSOC)){
$list .= "<div class=\"panel-heading\">
<div><a class=\"panel-title btn-block\" href=\"details.php?id=".$row['id']."\"><h3>".$row['id']." | ".$row['vidTitle']."</h3></a></div>
</div>
<div class=\"panel-body\">
<div class=\"imgCover\"><img class=\"imageCover\"src=\"" . $row['url'] . "\"></div>
<div class=\"vidSD\">" . $row['vidSD'] . "</div>
<div class=\"vidDetails\">
<hr class=\"style-two\">
<table>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtYear'] . "</strong></td><td class=\"vidDetailsTD\">" . $row['vidYear'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtCity'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidCity'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtGenre'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidZanr'] ." , ". $row['vidZanr2'] ." , ". $row['vidZanr3'] . "</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtQuality'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidQuality'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtTranslatedBy'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidTranslated'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtVideoTime'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidTime'] . "</td></tr>
</table>
</div></div>
<div class=\"panel-footer\">
<h6><strong>" . $lang['vsdAuthor'] . "</strong>".$row['addName']."</h6>
<div><h6><strong>" . $lang['vsdPublished'] . "</strong>" . $row['published'] . "</h6></div>
</div>";
}
mysqli_close($con);
?>
<div class="mainLeftCover">
<form action="view.php" method="GET">
<div class="input-group" style="width:180px">
<span class="input-group-addon" style="width:65px"><?php echo $lang['vidOrderTitleNew'] ?></span>
<select class="form-control" name = "order">
<option value="NEW">NEW</option>
<option value="OLD">OLD</option>
</select>
</div>
<?php
include_once 'inc/sortInc/sortType.php';
include_once 'inc/sortInc/sortGenre.php';
include_once 'inc/sortInc/sortGenre2.php';
include_once 'inc/sortInc/sortGenre3.php';
include_once 'inc/sortInc/sortYear.php';
include_once 'inc/sortInc/sortCity.php';
?>
<br><button type="submit" class="btn btn-default" style="width:180px">Submit</button>
</form>
<?php echo" <div id=\"pagination_controls\">" .$paginationCtrls. "</div>"; ?>
</div>
<?php
echo "<div class=\"maincover \" data-role=\"scrollbox\" data-scroll=\"vertical\">";
echo "<div class=\"panel panel-default\">";
echo" <div style=\"background-color:#fff\">" .$list. "</div>";
echo "</div></div>";
?>
Just for encase I gave full code. The problem is, that PAGINATION on it's own working fine... And ORDER function working fine separately as well. BUT TOGETHER they do not want to work. As result I have working pagination and if try to use sort it's just become empty page.
What I need..is somehow make sorting method working with pagination together, but i'm stuck how to do it.
I have this url when I'm using pagination:
http://example.net/view.php?pn=3
And this one when I'm using order:
http://example.net/view.php?order=NEW&vType=Film&vGenre=AnyGenre1&vGenre2=AnyGenre2&vGenre3=AnyGenre3&vYear=AnyYear&vCity=AnyCity
AND I need that URL will be like this:
http://example.net/view.php?pn=3&order=NEW&vType=Film&vGenre=AnyGenre1&vGenre2=AnyGenre2&vGenre3=AnyGenre3&vYear=AnyYear&vCity=AnyCity
That if you sort the page... it will remember how user was sort the list and open pages (pn=1, pn=2) will change.
May be some how save sort result and then use it in pagination..need to save it maybe when submit button pressed? But how can I save result from user???
<?php
session_start();
include_once 'dbconnect.php';
?>
<?php include ('head.php') ; ?>
<?php include ('menu.php') ; ?>
<?php if (isset($_SESSION['usr_id'])) { ?>
<?
$per_page = 15;
if (isset($_GET["page"])) {$page = $_GET["page"];}else {$page = 1;}
if (isset($_GET["order"])) {$order = $_GET["order"];}else {$order = username;}
$start_from = ($page-1) * $per_page;
if(isset($_GET['order']) && $_GET['order'] == 'user_id'){
$query = "select * from users order by user_id DESC limit $start_from, $per_page";}
if(isset($_GET['order']) && $_GET['order'] == 'username'){
$query = "select * from users order by username ASC limit $start_from, $per_page";}
if(isset($_GET['order']) && $_GET['order'] == 'posts'){
$query = "select * from users order by posts DESC limit $start_from, $per_page";}
$result = mysqli_query ($DBcon, $query);
$user_list_result = $DBcon->query("select * from users order by $order ASC limit 100");
$session = $_SESSION['usr_name'];
$query = $DBcon->query("SELECT * FROM users WHERE username='$session'");
$userRow=$query->fetch_array();
if ($userRow['userlevel'] > 0) {
?>
<div class="container">
<div class="row">
<div class="col-lg-6 col-sm-12">
<div class="panel panel-default panel-compact panel-wallet">
<div class="panel-body">
<center><h1>Userlist </h1></center>
<center>
<table >
<tr> <td width="20%"><b>ID </b></td>
<td width="20%"><b>Nickname </b></td>
<td width="20%"><b>Posts </b></td>
<td width="20%"><b>Message </b></td>
<td width="20%"><b>Click </b></td> </tr>
<?php
while($UserlistRow = $result->fetch_array())
{
echo "
<tr>
<td>$UserlistRow[user_id]</td>
<td><a href=user_profile.php?user=$UserlistRow[username]>$UserlistRow[username]</a></td>
<td>$UserlistRow[posts]</td>
</center>
<td><a href=msg_send.php?to=$UserlistRow[username]>Send Message</a></td>
<td><a href=user_click.php?to=$UserlistRow[username]>Click</a></td> ";?>
</tr>
<?php } ?> </table>
</center>
<?
$query = "select * from users order by $order";
$result = mysqli_query($DBcon, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<a href='user_list.php?page=" . ($_GET['page']+1) . "&order=" . ($_GET['order']) . "'>Next Page</a>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='user_list.php?page=".$i."&order=" . ($_GET['order']) . "'>".$i."</a> ";
};
echo "<a href='user_list.php?page=" . ($_GET['page']-1) . "&order=" . ($_GET['order']) . "'>Previous Page</a>";
?>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<?php } else { include('login_frame.php'); } ?>
<?php include ('footer.php') ; ?>
Related
How to change Pagination from 'per page' to only first and last pages?
i have a code for my table pagination. but now i have a problem. the pagination is showing EVERY page. but i got over 900 pages. ALSO: i need to use PDO i want the pagination to work like this: Image i dont know how to make this in my already excisting code: $per_page_html = ''; $page = 1; $start=0; if(!empty($_POST["page"])) { $page = $_POST["page"]; $start=($page-1) * ROW_PER_PAGE; } $limit=" limit " . $start . "," . ROW_PER_PAGE; $pagination_statement = $oConn->prepare($sql); $pagination_statement->execute(); $row_count = $pagination_statement->rowCount(); if(!empty($row_count)){ $per_page_html .= "<div style='text-align:center;margin:20px 0px;'>"; $page_count=ceil($row_count/ROW_PER_PAGE); if($page_count>1) { for($i=1;$i<=$page_count;$i++){ if($i==$page){ $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page current" />'; } else { $per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page" />'; } } } $per_page_html .= "</div>"; } $query = $sql.$limit; $pdo_statement = $oConn->prepare($query); $pdo_statement->execute(); $result = $pdo_statement->fetchAll();
I dont see your table and your query in your question so I will give 2 complete examples tested on my demo site, you need to change it to your own variables. Solution 1. Here is the example pagination for items belong to a category, for simple pagination : $perpage = "3"; //This limit of the page to show on each page $n_stmt = $pdo->prepare("SELECT * FROM categories"); $n_stmt->execute(); $total_posts = $n_stmt->rowCount(); $total_pages = ceil($total_posts/$perpage); $page = !empty($_GET['page']) && $_GET['page'] ? (int) $_GET['page'] : 1; if($page < 1) $page = 1; if($page > $total_pages) $page = $total_pages; $limit = ($page - 1) * $perpage; $pag_limit = 10; $stmt = $pdo->prepare("SELECT * FROM categories ORDER BY created DESC LIMIT :limit, :perpage"); $stmt->bindValue(":limit",$limit, PDO::PARAM_INT); $stmt->bindValue(":perpage",$perpage, PDO::PARAM_INT); $stmt->execute(); while($news = $stmt->fetch(PDO::FETCH_ASSOC)){ // Do what ever you want here } And pagination: <div class="pagination"> <?php if($page >1){?> First Preview <?php } for($i = $page - $pag_limit; $i < $page + $pag_limit + 1; $i++){ if($i > 0 and $i <= $total_pages){ if($i == $page){?> <?php echo $i;?> <?php }else{?> <?php echo $i;?> <?php } } ?> <?php } ?> <?php if($page != $total_pages){?> next Last <?php } ?> </div> Solution 2. Here is pagination for search result with your codes, as I said this code works on my demo site you need to change your own variables and its in pdo: define("ROW_PER_PAGE",10); //this goes on top of your page require_once("db.php"); $search_keyword = ''; if(!empty($_POST['search']['keyword'])) { $search_keyword = htmlspecialchars(strip_tags($_POST["search"]["keyword"]), ENT_QUOTES); } $sql = 'SELECT * FROM posts WHERE title LIKE :keyword OR descriptions LIKE :keyword OR subject LIKE :keyword ORDER BY id DESC '; /* Pagination Code starts */ $per_page_html = ''; $page = 1; $start=0; if(!empty($_POST["page"])) { $page = $_POST["page"]; $start=($page-1) * ROW_PER_PAGE; } $limit=" limit " . $start . "," . ROW_PER_PAGE; $pagination_statement = $pdo->prepare($sql); $pagination_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR); $pagination_statement->execute(); $row_count = $pagination_statement->rowCount(); if(!empty($row_count)){ $per_page_html .= "<div class=\"pagination\">"; $page_count=ceil($row_count/ROW_PER_PAGE); if($page_count>1) { for($i=1;$i<=$page_count;$i++){ if($i==$page){ $per_page_html .= "<input type=\"submit\" name=\"page\" value=" . $i . " class=\"btn-page current\" />"; } else { $per_page_html .= "<input type=\"submit\" name=\"page\" value=" . $i . " class=\"btn-page\"/>"; } } } $per_page_html .= "</div>"; } $query = $sql.$limit; $pdo_statement = $pdo->prepare($query); $pdo_statement->bindValue(":keyword", "%" . $search_keyword . "%", PDO::PARAM_STR); $pdo_statement->execute(); $result = $pdo_statement->fetchAll(); Your html part with pagination at the bottom and your result in form same as you can see <form name="frmSearch" action="search/" method="post"> <div class="searchf"> <input type="text" name="search[keyword]" class="field" value="<?php echo $search_keyword; ?>" id="keyword" maxlength="25"> <input type="submit" name="submit" class="searchf-btn" value="Ara"> </div> <?php if(!empty($result)) { foreach($result as $row) { ?> <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 } } ?> <div class="cl"> </div> //Here is pagination <?php echo $per_page_html; ?> </form> I am using seo urls in demo, you need to set htaccess for links, or change pagination links like so : your_page.php?page=$i. Both tested on my demo site and working, I used some filtering functions you can remove them.
Solution for pagination and $_post meaning
Hello i just finish my pagination and face a problem with my filter system i use from to filter and $_POST to extract data but the thing is when i go to second page the post meaning get to nothing and i am missing some data then in my case i got more then i filter it , i mean if i filter by location (london) i get 32 of 36 but when i go to second page i will get all 36 because $_post loses his meaning hare is my code and live page : My website Top code : $cat1 = ''; $perpage = 10; if(isset($_GET["catid"])){ $p1 = ''; $p2 = ''; $catid = $_GET["catid"]; $l1 = substr($catid,0,1); $l2 = substr($catid,1,1); $p1 = "CAT".$l1; if(!empty($l2)){ $p2 = "CAT".$l1."-".$l2; $p3 = $p2; } $cat1 = #$lang[$p1]; $cat2 = #$lang[$p2]; } $postid = ''; $userid = ''; $pricemin = ''; $pricemax = ''; $location = ''; if(isset($_POST["filter"])){ $pricemin = $_POST["min"]; $pricemax = $_POST["max"]; $location = $_POST["location"]; } ///////////////////////////////////////PAGINATION ////////////////// if(empty($p1) && empty($p2)){ $sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE p.id > 0 "; if(!empty($location)){ $sql .= "AND location='$location'"; } if(!empty($pricemin)){ $sql .= "AND price>='$pricemin' "; } if(!empty($pricemax)){ $sql .= "AND price<='$pricemax' "; } } else if(!empty($p2)){ $sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE catid='$p2' "; if(!empty($location)){ $sql .= "AND location='$location'"; } if(!empty($pricemin)){ $sql .= "AND price>='$pricemin' "; } if(!empty($pricemax)){ $sql .= "AND price<='$pricemax' "; } } else { $sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE p.catid LIKE '$p1%' "; if(!empty($location)){ $sql .= "AND location='$location'"; } if(!empty($pricemin)){ $sql .= "AND price>='$pricemin' "; } if(!empty($pricemax)){ $sql .= "AND price<='$pricemax' "; } } $res = mysqli_query($connect,$sql); $rows = mysqli_num_rows($res); $last = ceil($rows/$perpage); if($last < 1){ $last = 1; } $pagenum = 1; if(isset($_GET["pn"])){ $pagenum = preg_replace("#[^0-9]#", "", $_GET["pn"]); } if($pagenum < 1){ $pagenum = 1; } else if($pagenum > $last){ $pagenum = $last; } $limit = 'LIMIT ' .($pagenum - 1) * $perpage.',' .$perpage; $paginationCtrls = ''; if($last != 1){ if ($pagenum > 1) { $previous = $pagenum - 1; $paginationCtrls .= 'Previous '; for($i = $pagenum-4; $i < $pagenum; $i++){ if($i > 0){ $paginationCtrls .= ''.$i.' '; } } } $paginationCtrls .= ''.$pagenum.' '; for($i = $pagenum+1; $i <= $last; $i++){ $paginationCtrls .= ''.$i.' '; if($i >= $pagenum+4){ break; } } if ($pagenum != $last) { $next = $pagenum + 1; $paginationCtrls .= ' Next '; } } ?> and main html code with mysql query : <div class="fp"> <div class="filter"> <b style="padding-left: 10px;">Filters:</b> <form class="filterform" action="" method="post"><br> Location: <br> <input name="location" ><br> Price Range:<br> Min:<input type="text" name="min" size="5"> Max:<input type="text" name="max" size="5"><br><br> <input class="submit-button" type="submit" name="filter" value="Filter"> </form> </div> <div class="posts"> <div id="adcat"><?php if(!empty($cat2)){ ?> <a href="cat.php?catid=<?php echo $l1; ?>" ><?php echo $cat1." » "; ?></a><span><?php echo $cat2; ?></span> <?php } else { echo "<font color='grey'>".$cat1."</font>"; } ?> </div> <div id="totalrez"> <?php echo "Total: ".$rows; ?><br> <?php echo "Page".$pagenum." of ".$last; ?> </div> <br><br> <div id="detailformscat"> <?php if(empty($p1) && empty($p2)){ $sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE p.id > 0 "; if(!empty($location)){ $sql .= "AND location='$location'"; } if(!empty($pricemin)){ $sql .= "AND price>='$pricemin' "; } if(!empty($pricemax)){ $sql .= "AND price<='$pricemax' "; } $sql .= "$limit"; } else if(!empty($p2)){ $sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE catid='$p2' "; if(!empty($location)){ $sql .= "AND location='$location'"; } if(!empty($pricemin)){ $sql .= "AND price>='$pricemin' "; } if(!empty($pricemax)){ $sql .= "AND price<='$pricemax' "; } $sql .= "$limit"; } else { $sql = "SELECT * FROM posts p JOIN images i ON p.id = i.postid WHERE p.catid LIKE '$p1%' "; if(!empty($location)){ $sql .= "AND location='$location'"; } if(!empty($pricemin)){ $sql .= "AND price>='$pricemin' "; } if(!empty($pricemax)){ $sql .= "AND price<='$pricemax' "; } $sql .= "$limit"; } $res = mysqli_query($connect,$sql); $rows = mysqli_num_rows($res); while ($row = mysqli_fetch_assoc($res)) { $postid = $row["postid"]; ?> <div id="ads"> <div id="adfavcat"> <?php if(!isset($_SESSION["userid"])) { ?> <?php } else { $userid = $_SESSION["userid"]; $sql2 = "SELECT * FROM fav WHERE userid='$userid' AND postid='$postid' "; $res2 = mysqli_query($connect,$sql2); $rowcount = mysqli_num_rows($res2); if ($rowcount > 0){ ?> <?php } else { ?> <?php } } ?> </div> <div id="titlepic"> <?php echo $row["title"]; ?><br> <img src="<?php if(!empty($row["path1"])) { echo $row["path1"]; } else echo "image/noimage.png"; ?>" height="100px" width="150px"> </div> <div id="datescat"> <b>Date Added:</b> <?php echo date('m/d/Y H:i', $row["dateadded"]); ?><br> <b>Renew Date:</b> <?php if($row["renewdate"] > 0){ echo date('m/d/Y H:i', $row["renewdate"]); } ?><br> <b>Location:</b> <?php echo $row["location"]; ?><br> <b>Price:</b> <?php echo $row["price"]."£"; ?><br> </div> </div> <hr width="100%"> <?php } ?> <div id="paginationctrl"><br> <?php echo $paginationCtrls; ?> </div> </div> </div> </div> i need a possible solution for that , to catch post data and keep there until u change hare with a post method again or some other solution because now $_POST will be equal to null if u pass the second page on pagination
For this case you can instead change from $_POST to $_GET as this will be easier so solve your problem as well as any problems you might encounter in future. I think the majority of websites with pagination use variables in URL because it's much easier to track. Moreover, you're not sending any private data, so I don't see a reason why not switch to other method. You will have an option to use something like $_POST['page'] and accordingly to that you can retrieve other rows.
search and pagination not work
hello I try to combine the two scripts from the book PHP 6 and MySQL 5 for Dynamic Web Sites. I did search and pagination, but when I go to the next page - did not work. I posted two screenshots below. if someone could show me how I make a mistake I will be grateful. <?php require_once("../../includes/functions_2.php"); ?> <?php //database connect $dbhost = "localhost"; $dbuser = "root"; $dbpass = "1qazxsw2"; $dbname = "dw_bookstore"; $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); //sprawdzenie polaczenia if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } //zmaiana znako na utf8 if (!mysqli_set_charset($connection, "utf8")) { printf("Error loading character set utf8: %s\n", mysqli_error($connection)); } else { //printf("Kodowanie ustawione na: %s\n", mysqli_character_set_name($connection)); } ?> <?php // Number of records to show per page: $display = 3; // Determine how many pages there are... if (isset($_GET['p']) && is_numeric($_GET['p'])) { // Already been determined. $pages = $_GET['p']; } else { // Need to determine. #$query = $_GET['query']; $query4 = "SELECT COUNT(id) "; $query4 .= "FROM photographs "; $query4 .= "WHERE `nazwa` LIKE '%".$query."%' "; //$query .= "WHERE visible = 1 "; $result = #mysqli_query ($connection, $query4); $row = #mysqli_fetch_array ($result, MYSQLI_NUM); $records = $row[0]; // Count the number of records: if ($records > $display) { // More than 1 page. $pages = ceil ($records/$display); } else { $pages = 1; } } // End of p IF. // Determine where in the database to start returning results... if (isset($_GET['s']) && is_numeric($_GET['s'])) { $start = $_GET['s']; } else { $start = 0; } // Make the query: #$query = $_GET['query']; $query3 = "SELECT * "; $query3 .= "FROM photographs "; $query3 .= "WHERE `nazwa` LIKE '%".$query."%' "; $query3 .= "OR `kod` LIKE '%".$query."%' "; //$query .= "AND visible = 1 "; $query3 .= "ORDER BY id ASC LIMIT $start, $display "; $result3 = mysqli_query ($connection, $query3); ?> <?php // 2. Perform database query $query2 = "SELECT * "; $query2 .= "FROM photographs "; //$query2 .= "WHERE visible = 1 "; $query2 .= "ORDER BY nazwa ASC "; $result2 = mysqli_query($connection, $query2); // Test if there was a query error if (!$result2) { die("Database query failed."); } ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>List_n01</title> <link href="../../stylesheets/main_2.css" rel="stylesheet" type="text/css" media="screen, projection" /> </head> <body> <div id="wrapper"> <div id="header"> <h2>Cennik: Panel Administracyjny</h2> </div> <div id="mainContent"> <h1>Graphic Design</h1> <?php // Count the number of returned rows: $num = mysqli_num_rows($result2); if ($num > 0) { // If it ran OK, display the records. // Print how many rows there are: echo "<p>W bazie znajduje się $num pozycji.</p>\n"; ?> <form action="<?php echo $_SERVER ['PHP_SELF']; ?>" method="GET"> <fieldset> <ul class="formList"> <li> <input type="text" name="query" placeholder="Szukana fraza... " /> <input type="submit" value="Search" /> </li> </fieldset> </form> <table id="article"> <caption></caption> <colgroup> </colgroup> <tr> <th>Zdjęcie:</th> <th>Typ:</th> <th>Wielkość:</th> <th>Nazwa:Nazwa:</th> <th>Kod:</th> <th>Edytuj:</th> <th>Szczegóły:</th> <th>Usuń:</th> </tr> <?php // 3. Use returned data (if any) while($row = mysqli_fetch_assoc($result3)) { // output data from each row ?> <tr> <td><img src="../images/<?php echo $row['filename']; ?>" width="150" class="article" /></td> <td><?php echo $row['type']; ?></td> <td><?php echo size_as_kb($row['size']); ?></td> <td><?php echo $row['nazwa']; ?></td> <td><?php echo $row['kod']; ?></td> <td>Edytuj</td> <td>Detale</td> <td>{Usuń}</td> </tr> <?php } ?> </table> <?php // 4. Release returned data mysqli_free_result($result3); } else { // If no records were returned. echo '<p class="error">There are currently no rows.</p>'; } ?> <?php // Make the links to other pages, if necessary. if ($pages > 1) { echo '<br /><p>'; $current_page = ($start/$display) + 1; // If it's not the first page, make a Previous button: if ($current_page != 1) { echo 'Previous '; } // Make all the numbered pages: for ($i = 1; $i <= $pages; $i++) { if ($i != $current_page) { $distance = $current_page - $i; if (abs($distance) < 5){ echo '' . $i . ' '; } } else { echo $i . ' '; } } // End of FOR loop // If it's not the last page, make a Next button: if ($current_page != $pages) { echo 'Next'; } echo '</p>'; // Close the paragraph. } // End of links section. ?> </div> <div id="footer"> <p>Copyright <?php echo date("Y", time()); ?>, Cleoni</p></div> </div> </body> </html> <?php // 5. Close database connection mysqli_close($connection); ?>
you are facing issues because in your second url, the query parameter is missing, you should have also have the query=car parameter in get as the data that is been searched is searched with that parameter according to the script... Change code from around line 184-204 to the following // If it's not the first page, make a Previous button: if ($current_page != 1) { echo 'Previous '; } // Make all the numbered pages: for ($i = 1; $i <= $pages; $i++) { if ($i != $current_page) { $distance = $current_page - $i; if (abs($distance) < 5){ echo '' . $i . ' '; } } else { echo $i . ' '; } } // End of FOR loop // If it's not the last page, make a Next button: if ($current_page != $pages) { echo 'Next'; }
PHP - MySQL query with Pagination
How would I go about making a pagination script for this MySQL & PHP query. if (isset($_GET['c'])) { $c = $_GET['c']; } $query = mysql_query("SELECT * FROM Categories WHERE category = '$c' "); WHILE($datarows = mysql_fetch_array($query)): $id = $datarows['id']; $category = $datarows['category']; $code = $datarows['code']; endwhile; $query2 = mysql_query("SELECT * FROM Games WHERE category = '$code' "); WHILE($datarows_cat = mysql_fetch_array($query2)): $title = $datarows_cat['title']; $description = $datarows_cat['description']; $imgurl = $datarows_cat['image_name']; $category = $datarows_cat['category']; $views = $datarows_cat['view_count']; $pagename = $datarows_cat['pagename']; $featured = $datarows_cat['featured']; if ($featured =="1") {$f = "<img src='http://my-site.com/images/star.png' width='13px' title='Featured Game' /> Featured"; } else {$f = "";} if(is_int($views/2)) { $views = $views / 2; } else { $views = $views / 2 + .5; } if (strlen($description) > 95) { $desc= substr($description,0,95); $desmod = "$desc...<br/>- Read More"; } else {$desmod = "$description";} echo "$f - $title - $desmod<br/>"; endwhile; And when I visit http://my-site.com/categories/Action for instance, The code looks up that category in my category table, then once it gets the unique code for that category, It runs another query to find all games in another table with that category code. Currently, however, I have 200+ games loading for a single category which causes a great amount of loading time. Thanks for your help!
First of all find out how many games are there for a specific category change the line $query2 = mysql_query("SELECT * FROM Games WHERE category = '$code' "); to $sql="SELECT * FROM Games WHERE category = '$code' "; $query_count=mysql_query($sql); Add following after it $per_page =30;//define how many games for a page $count = mysql_num_rows($query_count); $pages = ceil($count/$per_page); if($_GET['page']==""){ $page="1"; }else{ $page=$_GET['page']; } $start = ($page - 1) * $per_page; $sql = $sql." LIMIT $start,$per_page"; $query2=mysql_query($sql); Then display the numbers of pages where you want <ul id="pagination"> <?php //Show page links for ($i = 1; $i <= $pages; $i++) {?> <li id="<?php echo $i;?>"><?php echo $i;?></li> <?php } ?> </ul> Use CSS for pagination this will do the trick
//database connation <?php $conn = new mysqli("localhost", "root", "","database_name"); ?> <!DOCTYPE html> <html>enter code here <head> <title>View Student Details</title> <h1 align="center"> Student Details </h1> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="bootstrap/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> </head> <body> <div class="row"> <div class="col-sm-2"></div> <div class="col-sm-8"> <form> <table class="table table-striped"> <tr> <th>Sr.No.</th> <th>Student ID</th> <th>Student Name</th> <th>Class</th> <th>Gender</th> <th>Birth of Date</th> <th>Contact No.</th> <th>Action</th> </tr> <?php $count=0; if(isset($_GET['page_count'])) { $count=1; $page_count=$_GET['page_count']-1; $count=$page_count*10; } $q="SELECT * from student_detail LIMIT $count,10"; $result=$conn->query($q); $j=0; while($data=$result->fetch_array()) { $j=$j+1; ?> <tr> <td><?php echo $j ?></td> <td><?php echo $data['std_id'] ?></td> <td><?php echo $data['std_name'] ?></td> <td><?php echo $data['std_class'] ?></td> <td><?php echo $data['gender'] ?></td> <td><?php echo $data['bod'] ?></td> <td><?php echo $data['contact'] ?></td> <td> <div class="row"> <div class="col-sm-12"> Delete Update </div> </div> </td> </tr> <?php } ?> </table> <ul class="pagination"> <?php $q="SELECT count(std_id) from student_detail"; $result=$conn->query($q); $data=$result->fetch_array(); $total=$data[0]; $total_page=ceil($total/10); if($total_page>1) { for($i=1;$i<=$total_page;$i++) { ?> <li class="active"><?php echo $i; ?></li> <?php } } ?> </ul> </form> <div class="col-sm-2"></div> </div> </div> </body> </html>
Pagiantion, it is working simple and easy <?php $sql = "SELECT COUNT(id) FROM contact_info"; $rs_result = $conn->query($sql); $row = mysqli_fetch_row($rs_result); $total_records = $row[0]; echo $total_records; $previous = 1; $total_pages = ceil($total_records / $limit); $next = $_GET["page"] + 1; $previous = $_GET["page"] - 1; $pagLink = "<span>"; if($previous ==0) { $prev = "<a href='javascript:void(0);' >Previous</a>"; } else { $prev = "<a href='http://homeacresfinefurniture.com/all-queries.php?page=".$previous."' style='color:black;'>Previous</a>"; }; echo $prev; "</span><div class='pagination'>"; for ($i=1; $i<=$total_pages; $i++) { $pagLink .= "<a href='http://homeacresfinefurniture.com/all-queries.php?page=".$i."'>".$i."</a>"; }; echo $pagLink; $nex = "<span><a href='http://homeacresfinefurniture.com/all-queries.php?page=".$next."' style='color:black;'>Next</a></span>"; echo $nex; "; </div>"; ?> Get all data from database. $limit = 1; if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; } $start_from = ($page-1) * $limit; $sql = "SELECT * FROM contact_info ORDER BY id desc LIMIT $start_from , $limit";
$page = 1; $limit = 10; $offset = ($limit * $page) - $limit; $query = mysqli_query( $connect, "SELECT * FROM Games WHERE category = '$code' limit $limit offset $offset" );
pagination panel should remain static
I've a search form in which a user enters the keyword and the results are displayed with pagination. everything works fine except for the fact that when the user clicks on the 'Next' button, the pagination panel disappears as well when the page loads to retrieve the data through ajax. How do I make the pagination panel static, while the data is being retrieved? search.html: <form name="myform" class="wrapper"> <input type="text" name="q" id="q" onkeyup="showPage();" class="txt_search"/> <input type="button" name="button" onclick="showPage();" class="button"/> <p> </p> <div id="txtHint"></div> </form> ajax: var url="search.php"; url += "?q="+str+"&page="+page+"&list="; url += "&sid="+Math.random(); xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); function stateChanged(){ if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } //end if } //end function search.php: $self = $_SERVER['PHP_SELF']; $limit = 3; //Number of results per page $adjacents = 2; $numpages=ceil($totalrows/$limit); $query = $query." ORDER BY idQuotes LIMIT " . ($page-1)*$limit . ",$limit"; $result = mysql_query($query, $conn) or die('Error:' .mysql_error()); ?> <div class="search_caption">Search Results</div> <div class="search_div"> <table class="result"> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> . . .display results. . . </tr> <?php } ?> </table> </div> <hr> <div class="searchmain"> <?php //Create and print the Navigation bar $nav=""; $next = $page+1; $prev = $page-1; if($page > 1) { $nav .= "<a onclick=\"showPage('','$prev'); return false;\" href=\"$self?page=" . $prev . "&q=" .urlencode($search_result) . "\">< Prev</a>"; $first = "<a onclick=\"showPage('','1'); return false;\" href=\"$self?page=1&q=" .urlencode($search_result) . "\"> << </a>" ; } else { $nav .= " "; $first = " "; } for($i = 1 ; $i <= $numpages ; $i++) { if($i == $page) { $nav .= "<span class=\"no_link\">$i</span>"; }else{ $nav .= "<a onclick=\"showPage('',$i); return false;\" href=\"$self?page=" . $i . "&q=" .urlencode($search_result) . "\">$i</a>"; } } if($page < $numpages) { $nav .= "<a onclick=\"showPage('','$next'); return false;\" href=\"$self?page=" . $next . "&q=" .urlencode($search_result) . "\">Next ></a>"; $last = "<a onclick=\"showPage('','$numpages'); return false;\" href=\"$self?page=$numpages&q=" .urlencode($search_result) . "\"> >> </a>"; } else { $nav .= " "; $last = " "; } echo $first . $nav . $last; ?> </div>
Not sure what you mean. Just change the result table not the whole page in showPage function.