PHP session is not persisting in pagination - php

PHP session variable loses data when used in a page that uses pagination script.
I'm using PHP pagination using $_GET[]. When the url looks like example.com/folder/index.php?page=2 the session does not work. But it works fine when the url is like example.com/folder/index.php.
How can I keep the session data persistent when using along with pagination script?
Edit:
Yes I am using session_start() at the top of the page.
session_start();
$page = (!isset($_GET['page']))? 1 : (int)$_GET['page'];
$prev_link = ($page - 1);
$next_link = ($page + 1);
/* Max results per page */
$max_results = 20;
/* Calculate the offset */
$from = (($page * $max_results) - $max_results);
$stmt3 = $dbh->prepare("SELECT COUNT(id) FROM my_table");
$stmt3->execute();
$row3 = $stmt3->fetch(PDO::FETCH_NUM);
if(!$row3)
{
die('Could not get data.');
}
$total_results = $row3[0];
$total_pages = ceil($total_results / $max_results);
$pagination = '';
/* Create a PREV link if there is one */
if($page > 1)
{
$pagination .= "<a class='pagination_link' href='http://example.com/folder/index.php?page=".$prev_link."' style='padding:1%;'>Previous</a>";
}
/* Loop through the total pages */
for($i = max(1, $page - 5); $i <= min($page + 5, $total_pages); $i++)
{
if(($page) == $i)
{
$pagination .= "<span style='padding:1%;font-weight:bold;'>$i</span>";
}
else
{
$pagination .= "<a class='pagination_link' href='index.php?page=".$i."' style='padding:1%;'>".$i."</a>";
}
}
/* Print NEXT link if there is one */
if($page < $total_pages)
{
$pagination .= "<a class='pagination_link' href='http://example.com/folder/index.php?page=".$next_link."' style='padding:1%;'> Next</a>";
}

In each of your php pages that you wish to utilise PHP Sessions, please make sure that the following line is at the top of your PHP pages
<?php session_start(); ?>
This ensures that session data is carried across pages

Related

how to pagify genre search result on the movie database

I have a website that I'm building on my localhost using the MVC design pattern. I have button on click that will display all the genres in TheMovieDatabase which I got using the TheMovieDatabaseAPI. On click of a genre I get data for Page 1 with 20 results. But, I couldn't figure out how to request the results for page 2. These requests are made using PHP.
I am assuming you are taking about pagination using, I am also assuming you are using mySQL as database, I am not sure which framework you are using,
Here is a function i use, you can build around this
function get_movie($page = 1){
global $database_connection;
$start = 0; //Don't modify this
$limit = 10; //set this to 20 to display 20 movies per page
$start = ($page - 1)* $limit;
//get the movie from the table
$sql = "SELECT genre FROM movie_table LIMIT $start, $limit";
$result = mysqli_query($database_connection, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div>$row['genre']</div>";
}
$movie_rows = mysqli_num_rows (mysqli_query($database_connection ,"SELECT * FROM movie_table"));
$total = ceil($testimony_rows / $limit);
if (isset($page)){
echo "<div>";
echo "<ul class='pager'>";
if($page > 1) {
echo "<a href='?page=".($page - 1)."' style='float: left;' class=' w3-sand w3-btn w3-margin w3-round'>Previous</a>";
}
for($i = 1; $i <= $total; $i++) {
if($i == $page) { echo "<li class='active current'>".$i."</li>"; }
else { echo "<li><a href='?page=".$i."'>".$i."</a></li>"; }
}
if($page != $total) {
echo "<a href='?page=".($page + 1)."' class='w3-btn w3-margin w3-sand w3-round'>Next</a>";
}
echo "</ul></div>";
}
}
you can use limit and offset to get the result for page 2.
Example :- if you are using query builder to get the results
$limit = 20;
$offset = 21;
$queryBuilder->select('d')
->from(<table name>, 'd')
->setMaxResults($limit)
->setFirstResult($offset)
->setParameter('limit', $limit)
->setParameter('offset', $offset);
If you are using raw query :
SELECT * FROM table LIMIT 20 OFFSET 21
Else you can use paginator too
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);
$totalItems = count($paginator);
$pagesCount = ceil($totalItems / $pageSize);
// now get one page's items:
$paginator
->getQuery()
->setFirstResult($pageSize * ($currentPage-1)) // set the offset
->setMaxResults($pageSize); // set the limit
foreach ($paginator as $pageItem) {
echo "<li>" . $pageItem->getName() . "</li>";
}

show page numbering in PHP

I am using this coed in PHP to show next and previous buttons for records in a mysql database:
$sql="SELECT * from customer";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$MaxRowsPerPage = 25;
$total_records = mysql_num_rows($rs);
$total_pages = ceil($total_records / $MaxRowsPerPage);
if(isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
}
$start_from = ($page-1) * $MaxRowsPerPage;
$sql.=" LIMIT $start_from, $MaxRowsPerPage";
I am echoing $total_records to show the total amount, how can i show the number from and to on the current page. for example, on page 1 it will be showing records 1 to 25 (because max rows per page is 25) and then page 2 will be showing records 26 to 50 and so on...
There a are many ways of doing this, but here's a simple pagination example I made. It will also show 1-25, 26-50 etc. It's heavily commented so it should be easy to understand.
<?php
// Connect to database
include 'includes/db_connect.php';
// Find total number of rows in table
$result = mysql_query("SELECT COUNT(*) FROM example_table");
$row = mysql_fetch_array($result);
$total_rows = $row[0];
// Set rows per page
$rows_per_page = 25;
// Calculate total number of pages
$total_pages = ceil($total_rows / $rows_per_page);
// Get current page
$current_page = (isset($_GET['p']) && $_GET['p'] > 0) ? (int) $_GET['p'] : 1;
// If current page is greater than last page, set it to last.
if ($current_page > $total_pages)
$current_page = $total_pages;
// Set starting post
$offset = ($current_page - 1) * $rows_per_page;
// Get rows from database
$result = mysql_query("SELECT * FROM example_table LIMIT $offset, $rows_per_page");
// Print rows
echo '<hr>';
while($row = mysql_fetch_array($result))
{
echo $row['id'].'<br />';
echo $row['text'];
echo '<hr>';
}
// Build navigation
// Range of pages on each side of current page in navigation
$range = 4;
// Create navigation link for previous and first page.
if ($current_page > 1)
{
$back = $current_page - 1;
echo ' PREV ';
if ($current_page > ($range + 1))
echo ' 1... ';
}
else
echo ' PREV ';
// Create page links, based on chosen range.
for ($i = $current_page - $range; $i < ($current_page + $range) + 1; $i++)
{
if ($i > 0 && $i <= $total_pages)
if ($i == $current_page)
echo ' [<strong>'.$i.'</strong>] ';
else
echo ' '.$i.' ';
}
// Create navigation link for next and last page.
if ($current_page != $total_pages)
{
$next = $current_page + 1;
if (($current_page + $range) < $total_pages)
echo ' ...'.$total_pages.' ';
echo ' NEXT ';
}
else
echo ' NEXT ';
?>

Call a function without its parameters

Below are the functions that am using to make reusable pagination. If you see the code below, theirs a function
generate_pages()
which is taking parameters from function
paged_controls()
But I would like to call the function generate_pages() without passing any parameters on body.php.
This is the error message am getting on body.php when calling function
generate_pages()
Warning: Missing argument 1 for generate_pages(), called in
E:\admin\snippets\body.php on line 11 and defined in
E:\admin\cores\pages.php on line 12
Notice: Undefined variable: limit in E:\xampp\htdocs\projects\hoplate\admin\cores\pages.php on line 16
Is that possible?
pages.php
<?php
function page_count(){
global $db;
$sql = "SELECT COUNT(pages_id) FROM pages";
$query = $db->SELECT($sql);
$rows = $db->FETCH_ROW();
foreach($rows as $row){
return $row[0];
}
}
function generate_pages($limit){
/* Run actual query now to get the records from database */
global $db;
$sql = "SELECT * FROM pages " . $limit;
$query = $db->SELECT($sql);
return $rows = $db->FETCH_OBJECT();
}
function paged_controls($page_rows = 1){
global $db;
/* Call the function page_count to get the total page count */
$row_count = page_count();
/* We use the ceil function to round the number to whole number */
$last = ceil($row_count / $page_rows);
/* Make sure that the last page cannot be less then 1 */
if($last < 1){
$last = 1;
}
/* Est. the page number variables */
$pagenum = 1;
/* Set the pagenum variables from URL else set it to 1*/
if(isset($_GET["paged"])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET["paged"]);
}
/* Make sure page number canoot be less then 1 */
if($pagenum < 1){
$pagenum = 1;
} else if($pagenum > $last){
$pagenum = $last;
}
/* Set the range of query to be excuted depend on our variables values set*/
$limit = 'LIMIT '.($pagenum - 1) * $page_rows . ','. $page_rows;
generate_pages($limit);
$paged_controls = "";
/* Only if theirs more then 1 page of results */
if($last != 1){
if($pagenum > 1){
$previous = $pagenum - 1;
$paged_controls .= 'Previous ';
/* Renders the left paged numbers */
for($i = $pagenum - 4; $i < $pagenum; $i++){
if($i > 0){
$paged_controls .= ''.$i.' ';
}
}
}
/* Render the current page the user is at */
$paged_controls .= ''.$pagenum.' ';
/* Renders the right paged numbers */
for($i = $pagenum + 1; $i <= $last; $i++){
$paged_controls .= ''.$i.' ';
if($i >= $pagenum + 4){
break;
}
}
if($pagenum != $last){
$next = $pagenum + 1;
$paged_controls .= 'Next ';
}
return $paged_controls;
}
}
?>
body.php
<?php
$pages = generate_pages();
foreach($pages as $page){
echo $pages_id = $page->pages_id . "<br/>";
}
?>
Only way I would see this working is adding a check.
function generate_pages($limit = null){
/* Run actual query now to get the records from database */
$gloab $db;
$sql = "SELECT * FROM pages " . isset($limit) ? "LIMIT $limit" : "";
$query = $db->SELECT($sql);
return $rows = $db->FETCH_OBJECT();
}
So now it could be run one of two ways
generate_pages();
or:
generate_pages(10);
Compare both of your function headers:
function generate_pages($limit)
function paged_controls($page_rows = 1)
PHP offers you to specify default arguments, just like C++ (you have to scroll down a bit to see the section).
Your paged_controls-function already does this and it is a great way of achieving what you want without editing the business logic within the function.
A default argument kicks in whenever you call a function without any parameters.
So, if you edit
function generate_pages($limit)
to (for example)
function generate_pages($limit = 'LIMIT 0,18446744073709551615')
and call the function via generate_pages(), PHP will automatically assume $limit = 'LIMIT 0,18446744073709551615'.
In this specific case, calling generate_pages without a parameter will retrieve all entries in the table you select from, as we tell the database to give us 18446744073709551615 entries from the beginning.
See the MYSQL manual on select/limit.

Passing $_GET (or $_POST) Variables With Pagination (SESSION not working)

I know this is a common problem as I have searched for answers before deciding to post, but I can't seem to figure out a solution.
PROBLEM: I have a pagination script (PHP) to use for my search results. As is apparently common, the first page results show fine, then fail when moving onto page 2, 3 etc.
I get an 'unknown index' error for each of my variables used in the search when clicking through to page 2, 3 etc.
So I $_GET these variables from my form:
$_SESSION['var1']= $_GET['var1'];
$_SESSION['var2']= $_GET['var2'];
$_SESSION['var3']= $_GET['var3'];
Points to note:
A Session has already been started in my header; I'm using $_GET because i prefer not having the 'resubmit' warning if a user goes 'back'; variables are all cleaned (just not shown in code as its long enough already); I have to use the $_GET variables with the WHILE loop as they calculate distance, age etc of each result.
My pagination script:
$limit = 4;
$query = "SELECT COUNT(*) as num FROM $tableName";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages['num'];
$stages = 3;
$page = mysql_escape_string(isset($_GET['page'])) ? (int)$_GET['page'] : 1;
if($page) {
$start = ($page - 1) * $limit;
} else {
$start = 0;
}
// Get page data
$query1 = "SELECT * FROM $tableName ORDER BY joindate DESC LIMIT $start, $limit";
$result = mysql_query($query1);
// Initial page num setup
if ($page == 0){$page = 1;}
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages/$limit);
$LastPagem1 = $lastpage - 1;
$paginate = '';
if($lastpage > 1) {
$paginate .= "<div class = 'hp1col'><div class='paginate'>";
$pagetotal = $total_pages.' Results';
// Previous
if ($page > 1){
$paginate.= "<a href='$targetpage?page=$prev'>Previous</a>";
} else {
$paginate.= "<span class='disabled'>previous</span>";}
// Pages
if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
}
// Next
if ($page < $counter - 1){
$paginate.= "<a href='$targetpage?page=$next'>Next</a>";
} else {
$paginate.= "<span class='disabled'>Next</span>";
}
$paginate.= "</div></div>";
}
while($row = mysql_fetch_array($result))
{
if (($part1 >= $_SESSION['var1']) AND ($part2 <= $_SESSION['var2']) AND ($part3 <= $_SESSION['var3'])) {
echo
"[Results]
}
}
echo $paginate;
I tried starting a new session in this if statement but it didn't help:
if ($page > 1){
$paginate.= "<a href='$targetpage?page=$prev'>Previous</a>";
} else {
$paginate.= "<span class='disabled'>previous</span>";}
I hope someone can help. I apologise for the slab of code in the question, but I thought it best just to put everything in for ease in, hopefully, someone being able to help.
Thanks
So you need to pass those query parameters through to the next page. If your page expects $_GET['var1'] to be present but you don't have ?var1=foo in the URL, it obviously won't work. The easiest way to handle this is http_build_query:
printf('Next',
$targetpage,
http_build_query(array('page' => 2) + $_GET));
This preserves all current values in $_GET and adds a page=2 parameter to it. Modify as needed for your case.

Having some trouble in my pagation code(PHP)

My table is posting and in that table, it shows all the posting people put in.
I am trying to make page navigation links at the bottom of the posts.
the function generateenter code here_page_links does all the work.
The code seem to be only showing the "<-" and "->" and not the link numbers. I think the function is only reading the $_GET['posting'] ==1.
(this code is from the Oreilly PHP/MySQL book. I am using it as practice)
function generate_page_links($cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "previous" link
if ($cur_page > 1) { //cur_page is just a number that is gotten from the url.
$page_links .= '<-- ';
}
else {
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
for ($i = 1; $i <= $num_pages; $i++) {
if ($cur_page == $i) {
$page_links .= ' ' . $i;
}
else {
$page_links .= ' ' . $i . '';
}
}
// If this page is not the last page, generate the "next" link
if ($cur_page < $num_pages) {
$page_links .= ' ->';
}
if ($cur_page == $num_pages){ //the last page
$page_links .= ' ->';
}
return $page_links; //need to return this variable in the function
}
// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 3; // number of results per page
$skip = (($cur_page - 1) * $results_per_page);
$query = "SELECT * FROM posting ORDER BY date_added DESC";
$data = mysqli_query($dbc, $query);
$total = mysqli_num_rows($data);
$num_pages = ceil($total / $results_per_page);
//Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
$result = mysqli_query($dbc, $query);
echo '<table>';
echo '<tr><td><b>Title</b></td><td><b>Date Posted</b></td></tr>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr><td><a href="ad.php?
posting_id='.$row['posting_id'].'
">'.$row['title'].'</a></td>';
echo '<td>'.$row['date_added'].'</td>';
//echo '<td>'.$row['name'].'</td></tr>';
}
echo '</table>';
// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
}
Well you have some problems here to start with:
You call the function with 4 variables
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
But the function only accepts two
function generate_page_links($cur_page, $num_pages)
If that's the code you're using, then it's probably going to crash because those variables are undefined.
Try deleting "$user_search, $sort," and see if that fixes it?

Categories