PHP 和 MySQL 分页:综合指南
问题:
您有一个 MySQL查询根据特定的“user_id”从“redirect”表中检索数据并按“timestamp”对结果进行排序。您需要实现分页才能每页显示 10 个结果。
解决方案:
在 PHP 中执行分页:
<code class="php"><?php // Insert your MySQL connection code here // Define variables $perPage = 10; $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1; $startAt = $perPage * ($page - 1); // Get total number of rows $query = "SELECT COUNT(*) as total FROM redirect WHERE user_id = '".$_SESSION['user_id']."'"; $r = mysql_fetch_assoc(mysql_query($query)); // Calculate total number of pages $totalPages = ceil($r['total'] / $perPage); // Generate pagination links $links = ""; for ($i = 1; $i <= $totalPages; $i++) { $links .= ($i != $page ) ? "<a href='index.php?page=$i'>Page $i</a> " : "$page "; } // Execute query with pagination applied $query = "SELECT * FROM 'redirect' WHERE 'user_id'= \''.$_SESSION['user_id'].' \' ORDER BY 'timestamp' LIMIT $startAt, $perPage"; $r = mysql_query($query); // Display results ... // Echo pagination links echo $links; // show links to other pages</code>
以上是如何在 PHP 和 MySQL 中为'重定向”表实现分页?的详细内容。更多信息请关注PHP中文网其他相关文章!