pagination using Rest API in php - php

I am trying to fetch data from mysql and display them category wise with pagination. I am getting the category wise result but when i change my page data of every category changed too i need to change the data of only category selected . i have setup multi category news option for user so they can add one news to multiple category .help me out here is my code what am trying.
<?php
include'../config.php';
// number of rows to show per page
$rowsperpage = 2;
$main = array();
$cat = array();
$qry = "SELECT * FROM app_category order by id DESC ";
$res = mysqli_query($con, $qry);
$records = mysqli_fetch_array($res, MYSQLI_ASSOC);
$rowcount = mysqli_num_rows($res);
if ($rowcount > 1) {
foreach ($res as $records) {
$cat = $records;
// lets find out how many rows are in the MySQL table
$sql = "SELECT COUNT(*) FROM app_news WHERE cat_id='" . $cat['id'] . "'";
$result = mysqli_query($con, $sql) or die(mysql_error());
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1; // default page number
}
// if current page is greater than total pages
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
}
// if current page is less than first page
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$qry = "SELECT * FROM app_news where cat_id='" . $cat['id'] . "' LIMIT $offset, $rowsperpage";
$res1 = mysqli_query($con, $qry);
$json1 = array();
while ($records1 = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$news_id = $records1['news_id'];
$news_title = $records1['title'];
$news_des = $records1['description'];
$news_des = htmlspecialchars_decode(str_replace(""", "\"", $news_des));
$news_image = $records1['image'];
$json1[] = array("news_id" => $news_id, "title" => $news_title, "image" => $imgapi . $news_image, "description" => $news_des);
}
$cat['All-news'] = array("total no of pages" => $totalpages, "data" => $json1);
$main[] = $cat;
unset($json1);
unset($json);
unset($cat);
}
unset($totalpages);
//header("Content-Type: application/json; charset=utf-8");
echo json_encode($main, JSON_UNESCAPED_SLASHES);
unset($main);
mysqli_close($con);
} else {
$minfo = array("success" => 'false', "message" => 'No result to display. Please add First category.');
$jsondata = json_encode($minfo);
print_r($jsondata);
mysqli_close($conn);
exit();
}

I have Split my code in two request get and post
get is for first time initialisation and then i use post method for getting scroll amount from app:
here is code :
<?php
include'../config.php';
$main = array();
$cat = array();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$rowsperpage = 5;
$qry = "SELECT * FROM app_category order by id DESC ";
$res = mysqli_query($con, $qry);
$records = mysqli_fetch_array($res, MYSQLI_ASSOC);
$rowcount = mysqli_num_rows($res);
if ($rowcount > 1) {
foreach ($res as $records) {
$cat = $records;
// lets find out how many rows are in the MySQL table
$sql = "SELECT COUNT(*) FROM app_news WHERE cat_id='" . $cat['id'] . "'";
$result = mysqli_query($con, $sql) or die(mysql_error());
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1; // default page number
}
// if current page is greater than total pages
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
}
// if current page is less than first page
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$qry = "SELECT * FROM app_news where cat_id='" . $cat['id'] . "' LIMIT $offset, $rowsperpage";
$res1 = mysqli_query($con, $qry);
$json1 = array();
while ($records1 = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$news_id = $records1['news_id'];
$news_title = $records1['title'];
$news_des = $records1['description'];
$news_des = htmlspecialchars_decode(str_replace(""", "\"", $news_des));
$news_image = $records1['image'];
$json1[] = array("news_id" => $news_id, "title" => $news_title, "image" => $imgapi . $news_image, "description" => $news_des);
}
$cat['All-news'] = array("total no of pages" => $totalpages, "data" => $json1);
$main[] = $cat;
unset($json1);
unset($json);
unset($cat);
}
unset($totalpages);
//header("Content-Type: application/json; charset=utf-8");
echo json_encode($main, JSON_UNESCAPED_SLASHES);
unset($main);
mysqli_close($con);
} else {
$minfo = array("success" => 'false', "message" => 'No result to display. Please add First category.');
$jsondata = json_encode($minfo);
print_r($jsondata);
mysqli_close($conn);
exit();
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
include_once'../config.php';
if (isset($_POST['cat_id'])) {
$rowsperpage = 5;
$catid = $_POST['cat_id'];
$qry = "SELECT * FROM app_category WHERE id='" . $catid . "' ";
$res = mysqli_query($con, $qry);
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$cat=$row;
}
// lets find out how many rows are in the MySQL table
$sql = "SELECT COUNT(*) FROM app_news WHERE cat_id='" . $cat['id'] . "'";
$result = mysqli_query($con, $sql) or die(mysql_error());
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
///Checkeing for page requested
if (isset($_POST['currentpage']) && is_numeric($_POST['currentpage'])) {
$currentpage = (int) $_POST['currentpage'];
} else {
$currentpage = 1; // default page number
}
// if current page is greater than total pages
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
}
// if current page is less than first page
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$qry = "SELECT * FROM app_news where cat_id='" . $catid . "' LIMIT $offset, $rowsperpage";
$res1 = mysqli_query($con, $qry);
$json1 = array();
while ($records1 = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$news_id = $records1['news_id'];
$news_title = $records1['title'];
$news_des = $records1['description'];
$news_des = htmlspecialchars_decode(str_replace(""", "\"", $news_des));
$news_image = $records1['image'];
$json1[] = array("news_id" => $news_id, "title" => $news_title, "image" => $imgapi . $news_image, "description" => $news_des);
}
$cat['All-news'] = array("total no of pages" => $totalpages, "data" => $json1);
$main[] = $cat;
unset($json1);
unset($json);
unset($cat);
echo json_encode($main, JSON_UNESCAPED_SLASHES);
unset($main);
unset($totalpages);
mysqli_close($con);
}
}

Related

How to get next ID on next page PHP

I want to read the different ID on different page, by using the prev/next button.
If I click next button, I want to get the next ID, if I click previous button, it will back to the previous ID. Following is what I want.
Example:
testnext_pre1.php?id=1&page=1
testnext_pre1.php?id=2&page=2
testnext_pre1.php?id=5&page=3
Here is my problem. As you can see, I get the same ID on every page because of my code. How to get the correct ID for the page?
Please take note: the IDs are not increase by sequence, as some contents might be deleted. So I don't want the answer something like "+1".
$rowsPerPage = 1;
if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
{
$pageNum = 1;
}
// preceding rows
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM news LIMIT $previousRows, $rowsPerPage";
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "<table border=1>\n";
echo "<tr><th>ID</th><th>Name</th><th>Password</th><th>Perm</th><th>Email</th>
<th>Date</th></tr>";
// print the results
while(list($id,$name,$pass,$perm,$email,$date) = mysql_fetch_array($result))
{
echo "<tr><td>$id</td><td>$name</td><td>$pass</td><td>$perm</td><td>$email</td>
<td>$date</td></tr>";
}
echo '</table>';
$query = "SELECT COUNT(id) AS numrows FROM news";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
$phpself = $_SERVER['PHP_SELF'];
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = "<div class=\"paginationbtn floatleft\">previous</div>";
$first = " [First Page] ";
}
else
{
$prev = ' previous ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$resultid = mysql_query("SELECT id FROM news");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
}
else
{
$next = ' [Next] ';
}
echo $prev . " " . $next;
Just get the previous and next ids from the database
if ($pageNum > 1)
{
//Get previous id using this query
SELECT id FROM news LIMIT $previousRows-1, $rowsPerPage
}
if ($pageNum < $lastPage)
{
//Get next id using this query
SELECT id FROM news LIMIT $previousRows+1, $rowsPerPage
}
Try the following sql query to get the next id,right now you are looping the news table and your next button will always have the same value
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$resultid = mysql_query("select id from news where id = (select min(id) from news where id > ".$_GET['id'].")");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
$prevresultid = mysql_query("select id from news where id = (select max(id) from news where id < ".$_GET['id'].")");
while($loopid=mysql_fetch_array($prevresultid))
{
$rowid = $loopid['id'];
$prev= " <div class=\"paginationbtn floatleft\">next</div> ";
}
}
Note: you will need mysqli and prepared statements to secure your code
if you want to set pagination than no need of next id it will mange by query only . and in query we change only offset .
for e.g each page display 3 records so our limit is 3
now if we on first page than our fetch record query is(on first page offset is always 0)
so offset is 0 and limit is 3
SELECT fieldName FROM tableName LIMIT offset,limit
for second page now current offset is 3 so
prev is current_offset minus limit (3-3) so prev offset is 0
next is current_offset plus limit (3+3) so next offset is 6
now in 3rd page current offset is 6
prev is current_offset minus limit (6-3) so prev offset is 3
next is current_offset plus limit (6+3) so next offset is 9
try this one
<?php
$rowsPerPage = 1;
if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
{
$pageNum = 1;
}
// preceding rows
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM news LIMIT $previousRows, $rowsPerPage";//offset,limit
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "<table border=1>\n";
echo "<tr><th>ID</th><th>Name</th><th>Password</th><th>Perm</th><th>Email</th>
<th>Date</th></tr>";
// print the results
while(list($id,$name,$pass,$perm,$email,$date) = mysql_fetch_array($result))
{
echo "<tr><td>$id</td><td>$name</td><td>$pass</td><td>$perm</td><td>$email</td>
<td>$date</td></tr>";
}
echo '</table>';
$query = "SELECT COUNT(id) AS numrows FROM news";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
$phpself = $_SERVER['PHP_SELF'];
if ($pageNum > 1)//current page > 1
{
$page = $pageNum - 1;
$prev = "<div class=\"paginationbtn floatleft\">previous</div>";
$first = " [First Page] ";
}
else
{
$prev = ' previous ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$next_row=$previousRows+1;
$resultid = mysql_query("SELECT id FROM news LIMIT $next_row,1");
while($loopid=mysql_fetch_array($resultid))
{
$rowid = $loopid['id'];
$next = " <div class=\"paginationbtn floatright\">next</div> ";
}
}
else
{
$next = ' [Next] ';
}
echo $prev . " " . $next;

Display a new div after every number of records fetch from database in MySQL

I want to create a div for ads on a project I'm working on. I want the div to show after 8 records is fetch from the database.
My select statement:
$query = mysql_query("SELECT * FROM posts WHERE `username` = '$followe' OR `user_id` = ' $get_id' ORDER BY date_added DESC LIMIT 15 ");
$newsCount = mysql_num_rows($query); // Count the output amount
if ($newsCount > 0) {
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$user_post_id = $row["user_id"];
$username = $row["username"];
$text = $row["texts"];
$profile_pix = $row["profile_pix"];
}
}
You need to add a counter for your while loop and echo the HTML string when the counter is divisible by 8:
<?php
$query = mysql_query("SELECT * FROM posts WHERE `username` = '$followe' OR `user_id` = ' $get_id' ORDER BY date_added DESC LIMIT 15 ");
$newsCount = mysql_num_rows($query); // Count the output amount
if ($newsCount > 0) {
$rowcount=1;
$divhtml = "<div></div>";
while ($row = mysql_fetch_assoc($query)){
if ($rowcount % 8 == 0) {
echo $divhtml;
}
$rowcount++;
$id = $row["id"];
$user_post_id = $row["user_id"];
$username = $row["username"];
$text = $row["texts"];
$profile_pix = $row["profile_pix"];
}
}
?>
You should change the content of variable $divhtml, with your own ad HTML.
Use an accumulator pattern such as this.
$i = 0
while($row = mysql_fetch_assoc($query)){
$i++;
if(i == 8) {
// DO WHATEVER
}
$id = $row["id"];
$user_post_id = $row["user_id"];
$username = $row["username"];
$text = $row["texts"];
$profile_pix = $row["profile_pix"];
}

keep post variable in php pagination

I have a php pagination page with post submit by user to search something, query mysql in first page is ok, but in NEXT page, i have get white blank page.
Below is the paging code.
$_SESSION['nationality'] = $_POST['nationality'];
$reclimit = 2;
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$start = (($page-1) * $reclimit);
$sql = "SELECT userid, name, LEFT(hkid, 4) as hkid, description, nationality, photo_1, photo_2, photo_3 FROM $tbl_name WHERE `nationality` LIKE '%$_SESSION[nationality]%'";
$records = $con->query($sql);
$total = $records->num_rows;
$tpages = ceil($total / $reclimit);
$rec = "SELECT userid, name, LEFT(hkid, 4) as hkid, description, nationality, photo_1, photo_2, photo_3 FROM $tbl_name WHERE `nationality` LIKE '%$_SESSION[nationality]%' LIMIT $start, $reclimit";
$records = $con->query($rec);
while ($row = mysqli_fetch_assoc($records)){
// Loop record
}
// Paging
echo '<ul class="pagination pagination-lg">';
for( $i=1; $i <= $tpages; $i++ ) {
$active = $i == $page ? 'class="active"' : '';
echo "<li $active ><a href='$_SERVER[PHP_SELF]?page=" .$i. "'>" .$i. "</a></li>";
}
echo '</ul>';
This works for me:
<?php
$limit =3;
if (!isset($_GET['pg'])) {
$pg = 1;
} else {
$pg = $_GET['pg'];
}
$start = ($pg - 1 ) * $limit;
$sql = "SELECT * FROM tableName LIMIT $start , $limit";
?>

PHP pagination script not work for search

I used this code in my all pages. Everywhere this code work well. In case of my search page this code count all page by search words but when I click next(2nd or 3rd) page, its cannot display any item. That means sql query for 2nd or 3rd or any others pages not worked. No error also. Pagination page url goes well also.
My Search code:
if(isset($_POST['searchword'])){
$w = mysqli_real_escape_string($dbh, $_POST['searchword']);
$q = strip_tags($w);
$q = trim ($w);
$limit = 12;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM search_data WHERE MATCH(detail) AGAINST('+$q*' IN BOOLEAN MODE) ORDER BY id ASC LIMIT $start_from, $limit";
$execute = $dbh->query("$sql");
$rowcount = $execute->num_rows ;
if ($rowcount > 0 ) {
$row = $dbh->query($sql) ;
while ($row = $execute->fetch_assoc()) {
$detail = $row['detail'];
$url = $row['url'];
echo $detail;
}
}
}
//Pagination
$sql = "SELECT COUNT(id) FROM search_data WHERE MATCH(detail) AGAINST('+$q*' IN BOOLEAN MODE)";
$result = mysqli_query($dbh,$sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
if($total_records > 0){$total_pages = ceil($total_records / $limit); }
$pagLink = "<ul class='pagination'>";
if(!empty($total_pages)){for ($i=1; $i<=$total_pages; $i++) {
$pagLink .= "<li><a href='".$thispage."?page=".$i."'>".$i."</a> </li>";
};
echo $pagLink . "</ul>";
}

PHP paging, viewing a certain page first

This is my script for the paging on my site when the user clicks on a league.
The league is then echoed to the screen, and if the league is over 3 rows then it splits it up in to several pages.
What I am doing after is depending on where the user is in the league (the SQL query is using ORDER BY the total points column in the table), e.g if the user is on page one of the league table then for it to display that page first, but if the user is on page 3 of the league table then for that page to displayed first.
Does anyone know a way in order for me to achieve this?
//Recently updated from answer
$sql="SELECT members.username, members.total_points FROM members, members_leagues WHERE members.username = members_leagues.username AND
members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC";
$result=mysql_query($sql);
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row($result)){
if ($row[username] == $_SESSION[username]) {
$team_position = $i;
$found = true;
}
$i++;
}
$rowsPerPage = 3;
$pageNum = ceil($i/$rowsPerPage);
//end of recently updated
if(isset($_GET['page']))
$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$counter = $offset + 1;
$query = " SELECT members.username, members.teamname, members.total_points, FROM members, members_leagues WHERE members.username = members_leagues.username AND members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC " . " LIMIT $offset, $rowsPerPage";
$result = mysql_query($query) or die('Error, query failed');
echo "<h3 style=\"color:red;\">$chosenleague</h3>";
echo "<table>";
echo "<tr><th>Position</th>";
echo "<th>Team</th>";
echo "<th>Points/Overall</th>";
echo "<th>Points/Last Race</th>";
echo "<th>Team Setup</th></tr>";
while($row = mysql_fetch_array($result))
{
if($row[username] == $_SESSION[username])
echo "<tr style=\"color:red;\"><td>";
else
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $row[teamname];
echo "</td><td>";
echo $row[total_points];
echo "</td><td>";
echo "</td><td>";
echo "</td></tr>";
$counter++;
}
echo "</table>";
$query = "SELECT COUNT(members.username) AS numrows FROM members, members_leagues WHERE members.username = members_leagues.username
AND members_leagues.sub_league = '$chosenleague'";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxPage = ceil($numrows/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
$nav = '';
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " << Prev ";
$first = " First ";
}
else
{
$prev = '';
$first = '';
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " Next >> ";
$last = " Last ";
}
else
{
$next = '';
$last = '';
}
echo "<div id=\"pagenum\">Page $pageNum of $maxPage ". $first . $last . $prev . $next ."</div>";
You can do it via mysql or php:
With PHP:
Found the position of the requested record in the array, then calculate the page you have to extract and execute the corresponding query. Something like.
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row) {
if ($row['team'] == 'team_your_searching_for') {
$team_position = $i;
$found = true;
}
$i++;
}
//calculate $top and $bottom
...
$sql = "SELECT * FROM members LIMIT $top, $bottom;";
...
With MySQL:
You can create a query that generates an autoincrement value and another that selects from the other's result. I mean
-- get the the selected member's position
SELECT team, pos FROM (SELECT team, points, #position = #position + 1 AS pos FROM members ORDER BY points) WHERE team = #the_team_your_searching_for;
-- get the nr of members
SELECT COUNT(*) FROM members;
...
-- calculate the page you wanna extract (#top, #bottom), and extract it
SELECT * FROM members LIMIT #top, #bottom;

Categories