【问题标题】:PHP session is not persisting in paginationPHP会话没有持续分页
【发布时间】:2014-05-22 09:54:41
【问题描述】:

PHP 会话变量在使用分页脚本的页面中使用时会丢失数据。

我正在使用$_GET[] 进行 PHP 分页。当 url 看起来像 example.com/folder/index.php?page=2 时,会话不起作用。但是当 url 类似于 example.com/folder/index.php 时,它可以正常工作。

与分页脚本一起使用时,如何保持会话数据持久化?

编辑:

是的,我在页面顶部使用session_start()

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

【问题讨论】:

  • 你确定 session_start();在每一页的顶部?
  • 我已经发布了代码并在每一页的顶部使用了session_start()

标签: php session pagination


【解决方案1】:

在您希望使用 PHP 会话的每个 php 页面中,请确保以下行位于您的 PHP 页面顶部

<?php session_start(); ?>

这确保了会话数据跨页面传输

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 2012-03-29
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多