如何在分页中获取特定的行页码

时间:2014-09-18 04:15:48

标签: mysqli pagination

我对MySQL分页有疑问。用户的记录显示在具有许多其他用户记录的表上。并对表进行排序/分页。现在我需要在用户登录后直接显示包含用户行的页面。我怎样才能做到这一点?

create table t_users (id int auto_increment primary key, username varchar(100)); insert t_users(username) values ('jim'),('bob'),('john'),('tim'),('tom'), ('mary'),('elise'),('karl'),('karla'),('bob'), ('jack'),('jacky'),('jon'),('tobias'),('peter');

我搜索了谷歌但未找到答案,所以请帮助

1 个答案:

答案 0 :(得分:0)

这有两个步骤:

<强> 1。确定排序表中行的位置。

https://stackoverflow.com/a/7057822/2391142

复制并调整

使用此SQL ...

SELECT z.rank FROM (
SELECT id, @rownum := @rownum + 1 AS rank
FROM t_users, (SELECT @rownum := 0) r
ORDER BY id ASC
) as z WHERE id=1;

...用您的实际排序顺序替换ORDER BY id ASC。并将WHERE id=1中的数字1替换为index.php中提供的数字?u = id url。

<强> 2。根据行的位置确定页码。

使用此PHP确定所需的页码...

$rows_per_page = 50;
$user_row_position = [result you got from step 1];
$page = ceil($user_row_position / $rows_per_page);

...用你真实的每页行数限制替换50,并将真正的SQL结果放在$ users_row_position中。

瞧。您将$page变量中包含目标页码,希望您可以从那里获取目标页码。

修改

在评论中进一步讨论之后,使用PHP的这一点:

$page = 0;
$limit = 10;

// If a user ID is specified, then lookup the page number it's on.
if (isset($_GET['u'])) {
    // Check the given ID is valid to avoid SQL injection risks.
    if (is_numeric($_GET['u'])) {
        // Lookup the user's position in the list.
        $query = mysqli_fetch_array(mysqli_query($link, "SELECT z.rank FROM (SELECT id, @rownum := @rownum + 1 AS rank FROM sites, (SELECT @rownum := 0) r WHERE online='0') as z WHERE id=" . $_GET['u']));
        $position = $query[0];
        if (is_numeric($position)) {
            // Convert the result to a number before doing math on it.
            $position = (int) $position;
            $page = ceil($position / $limit);
        }
    }
}

// If a page number is specified, and wasn't already set by looking a user, then lookup the real starting row.
if ($page == 0 && isset($_GET['page'])) {
    // Check your given page number is valid too.
    if (is_numeric($_GET['page'])) {
        $page = (int) $_GET['page'];
    }
}

// Notice that if anything fails in the above checks, we just pretend it never
// happened and keep using the default page and start number of 0. 

// Determine the starting row based off the page number.
$start = ($page - 1) * $limit;

// Get the list of sites for the provided page only.
$query = mysqli_query($link, "SELECT * FROM sites WHERE online='0' LIMIT " . $start . ", " + $limit);
while ($row = mysqli_fetch_array($query)) {
    // Stuff to render your rows goes here.
    // You can use $row['fieldname'] to extract fields for this row.
}