我没有再发布这篇文章,而是决定在这里重新编写并详细说明。
我收到了来自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个更新(并且每周五添加一个新的更新,并且每周五删除一个旧更新),但我只能在每个星期五显示在页面上。我意识到这不是一个分页问题,因为这是编写查询基本上做两个函数。
可以使用子查询来完成吗?我可以使用jQuery滑块或等效的分页进行分页,但我真的想避免这种情况。
非常感谢!
答案 0 :(得分:1)
要在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
然后使用您的数据库查询而不做任何更改。
然后在你的视图中添加页面链接(如果以上执行上述代码,则此代码有效):
<?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
替换为脚本的正确文件名)
我为当前所选页面的页面锚点active
添加了一个类,但无论如何你都可以这样做。
答案 1 :(得分:0)
我认为这就是你要求的......使用这个“功能”你可以“切换”更多选项,但我认为你真的不需要它......只需改变$limit=
数字就可以满足你的需求。 / p>
<?php
$starttime = strtotime("28 December 2012"); // a recent Friday
$week = 7 * 24 * 60 * 60; // time value of a week
$posts = 200; // number of posts in your db
//$limit = 52; // number of shown posts
if($posts > 100) // or you can enter here $posts == 200, but it is better 2 leave it on "automatic"..
{
$limit = 52; //or as many you like like 30
}
else
{
$limit = 6; // or as many you like ie 10
}
$offset = floor((time()-$starttime)/$week); // rounds down difference in weeks from startdate until now
while ($offset>$posts-$limit) $offset = $offset - ($posts-$limit);
// this will make the cycle start over when you have reached the end (ie offset 148)...
?>