php - 可以更改此查询以执行两个功能吗?

标签 php mysql database pagination

我决定在这里重新编写并详细说明,而不是再次发布此内容。

我从 jtheman 收到了以下代码,它允许我从数据库中选择 52 个更新,并每周添加一个新的并删除旧的。它工作起来绝对完美。

他的代码:

$starttime = strtotime("28 December 2012"); // a recent Friday
  $week = 7 * 24 * 60 * 60; // time value of a week
  $posts = 185; // number of posts in your db
  $limit = 52; // number of shown posts
  $offset = floor((time()-$starttime)/$week); // rounds down difference in weeks from startdate until now
  while ($offset>$posts-$limit) $offset = $offset - ($posts-$limit); 
  // this will start over when you have reached the end of the cycle ie offset 148...

我的查询:

// retrieve all update details
$conn = dbConnect('query');
$sql = "SELECT *
FROM updates
WHERE flag_live = 'Y'
ORDER BY update_id DESC
LIMIT ".$offset.",".$limit;
$result = $conn->query($sql) or die(mysqli_error());
$uInfo = $result->fetch_assoc();

同样,这非常有效。新问题是我在一页上收到 52 个更新,我希望能够设置(比如每页 4 个)并滚动浏览 13 页,而不是一页很长。

因此,我想要做的是更改此查询,以便选择 52 个更新(并且每周五添加一个新更新并删除一个旧更新),但我一次只能显示 4 个更新在页面上。我意识到这不是一个分页问题,​​而是编写查询来本质上执行两个函数。

这可以通过子查询来完成吗?我可以只使用 jQuery slider 或等效工具来进行分页,但我真的想避免这种情况。

非常感谢!

最佳答案

要在 PHP 代码(服务器端)中解决此问题,您可以添加一个 url 参数 ?page=x,其中 x 是您的页码。

计算中几乎相同:

$starttime = strtotime("28 December 2012"); // a recent Friday
$week = 7 * 24 * 60 * 60; // time value of a week
$posts = 185; // number of posts in your db
$totallimit = 52; // number of shown posts (on all pages)
$limit = 4; // number of posts on each page.
$offset = floor((time()-$starttime)/$week); // rounds down difference in weeks from startdate until now
while ($offset>$posts-$totallimit) $offset = $offset - ($posts-$totallimit); 
// this will start over when you have reached the end of the cycle ie offset 148...

// get the page number (or set it to 0 if not set)
if (isset($_GET['page']) && intval($_GET['page'])) $page=intval($_GET['page']);
else $page = 0;

$offset = $offset + ($page*$limit); // correct the offset according to the page number

然后使用您的数据库查询而不进行任何更改。

然后在您的 View 中添加页面链接(如果之前执行过上述代码,则此代码有效):

<?php for($p=0;$p<ceil($totallimit/$limit);$p++): ?>
   <a href="mypage.php?page=<?php echo $p; ?>" <?php if ($p==$page) echo 'class="active"'; ?>>Page <?php echo $p+1; ?></a> |
<?php endfor; ?>

(将 mypage.php 替换为脚本的正确文件名)

我向当前所选页面的页面 anchor active 添加了一个类,但您可以按照自己喜欢的方式执行此操作。

关于php - 可以更改此查询以执行两个功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14107961/

相关文章:

mysql - 使用另一个表更新表

java - Hibernate 无法创建与数据库服务器的连接

c# - 哪种sql查询在SQL注入(inject)方面更安全

javascript - 浏览器有时会添加 <tbody>

MySQL Left Join 表 where 连接表可以为空,但有where条件

php - PDO/Codeigniter 准备时出错

mysql - Mysql中如何关联表

C#:映射 IDataReader.GetTableSchema() 和 DbType 枚举?

php - 为什么 PHP curl 不起作用?当它从命令行 curl 工作时?

java - 将数据保存在数据库或 session 中