我所说的一系列页面是指可以使用上一页、下一页或12、3/kbd>内容是10首歌曲的列表,要查看更多信息,用户只需单击下一步。我计划使用PHP和MySQL。我需要你对如何进行这项工作的意见(不是明确要求代码,而是可能用代码补充的个人意见)。谢谢
MySQL提供了LIMIT X,Y
关键字,该关键字已经完成了大部分工作。CCD_ 2总是起始位置,而CCD_。
例如,如果您有一个搜索表单,并且用户搜索pop类型的歌曲,则可以执行类似SELECT name, artist, ... FROM songs WHERE genre = 'pop' LIMIT 0,10
的操作。这将返回从位置0开始的搜索结果的10首歌曲。那将是你的第一页。对于第2页,只需使用LIMIT 10,10
再次运行相同的查询。
使用此功能,您可以创建上一个和下一个按钮:
HTML
<a href="search.php?query=pop&page=1">Previous</a>
<a href="search.php?query=pop&page=3">Next</a>
PHP
$page = isset($_GET['page']) ? intval($_GET['page'] : 1;
$start = ($page - 1) * 10;
$query = "SELECT name, artist, ... FROM songs WHERE genre = 'pop' LIMIT $start,10";
该技术称为分页。这里有一个PHP助手类,可以帮助您进行分页:
<?php
// This is a helper class to make paginating
// records easy.
class Pagination {
public $current_page;
public $per_page;
public $total_count;
public function __construct($page=1, $per_page=20, $total_count=0){
$this->current_page = (int)$page;
$this->per_page = (int)$per_page;
$this->total_count = (int)$total_count;
}
public function offset() {
// Assuming 20 items per page:
// page 1 has an offset of 0 (1-1) * 20
// page 2 has an offset of 20 (2-1) * 20
// in other words, page 2 starts with item 21
return ($this->current_page - 1) * $this->per_page;
}
public function total_pages() {
return ceil($this->total_count/$this->per_page);
}
public function previous_page() {
return $this->current_page - 1;
}
public function next_page() {
return $this->current_page + 1;
}
public function has_previous_page() {
return $this->previous_page() >= 1 ? true : false;
}
public function has_next_page() {
return $this->next_page() <= $this->total_pages() ? true : false;
}
}
?>
在构造SQL中的应用
$total_count = $db->get_var( "SELECT COUNT(*) FROM songs" );
$per_page = 10;
$current_page = $page;
$pagination = new Pagination($current_page, $per_page, $total_count);
$all = $db->get_results("SELECT * FROM songs ORDER BY id DESC LIMIT {$per_page} OFFSET {$pagination->offset()}");