如何在MySQL中获取带有帖子ID的帖子页面

时间:2017-10-17 14:32:06

标签: php mysql

我写了一个查询来获取我的帖子与DESC命令,因为你看到它的限制,每页显示10个帖子 但我怎么能找到" pid = 18"在什么页面?

TABLE:

pid, posterid, content
1 , 26 , blabla
2 , 8 , sec balnla
3 , 9 , lollll
4 , 26 , orddddd
5 , 10 , sssssdsd
...

PHP:

function getComments($poster){
    $sql = "SELECT * FROM table WHERE posterid = $poster"
    $smt = $db->query($sql); 
    $total = $smt->rowCount();

    $result = $db->prepare($sql . " ORDER BY pid DESC $limit");
    $result->execute();
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $Comments[] = $row;
    }
    return [
        'comments' => $Comments,
        'total' => $total
    ];
}

需要的功能:

$poster = 26;
$pid = 18;
$posttperpage = 10;

public function getPostPage($pid, $poster, $posttperpage)
{
    $page = '';

    $totlaPosts = getComments($poster)['total']; //70

    $pages = $totlaPosts / $posttperpage; //7

    for($i=0, $i<$totlaPosts, $i--)
    {
        // ?????
        // i confuzed no idead what can i do :(

    }
    return $page; //it must be 2
}

4 个答案:

答案 0 :(得分:1)

由于pid不一定一致(您可能删除了某些行),因此您应该有另一个查询。

$stmt = $db->prepare("SELECT COUNT(1) FROM table WHERE pid <= ? AND poster = ?");
$stmt->execute([$pid, $poster]);
$count = $stmt->fetchColumn();

echo ceil($count / $posttperpage);

答案 1 :(得分:0)

如果您要确定帖子的页面:

body{
background-image: url(https://preview.ibb.co/ntRarR/watermark3.png); text-align: center;background-repeat:no-repeat;background-size:cover;}

这是你要找的吗?

答案 2 :(得分:0)

LIMIT 0,10中,每页有10个项目,对吧?如果您想跟踪您正在查看的页面,则需要一个行为如下的变量:

$range = 10;
$currentPage = 2;
$offset = $range * ($currentPage - 1);

在您的查询中,您可以将该0更改为$offset,如果您在此查询中找到了结果,则表示您的pid位于第2页,您还可以增加{{1}如果你无法找到你的结果,那么就是1。

答案 3 :(得分:0)

这个算法很简单,

您需要知道行的总数,特定帖子的位置以及每页的帖子数量。

你喜欢这样:

楼层(position_of_you_post / number_total_of_post * number_of_post_per_page)

所以如果你有100个帖子,每页10个帖子,你的帖子是51号,你可以这样做:

51/100 * 10 = 5.1

所以帖子在第5页