【问题标题】:How to Create a Series of Webpages [closed]如何创建一系列网页[关闭]
【发布时间】:2014-11-08 01:19:42
【问题描述】:

一系列页面是指可以使用 PreviousNext12,3, ... 内容为10首歌曲的列表,用户可以点击Next查看更多内容。我打算使用 PHP 和 MySQL。我需要你对如何去做的意见(不是明确要求代码,而是可能补充代码的个人意见)。谢谢!

【问题讨论】:

  • 你的意思是像 /page/2... 之类的吗?
  • 那么,关于分页的问题?
  • 现在我更喜欢无限滚动而不是分页。
  • 哦!所以这就是他们所说的,分页。谢谢! @草莓

标签: php mysql ajax


【解决方案1】:

MySQL 提供了LIMIT X,Y 关键字,它已经完成了大部分工作。 X 始终是起始位置,Y 始终是要选择的行数。

例如,如果您有一个搜索表单,并且用户搜索pop 类型的歌曲,您可以执行SELECT name, artist, ... FROM songs WHERE genre = 'pop' LIMIT 0,10 之类的操作。这将返回从位置 0 开始的 10 首搜索结果歌曲。那将是您的第 1 页。对于第 2 页,您只需再次运行相同的查询,但使用LIMIT 10,10

使用它,您可以创建 PreviousNext 按钮:

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";

【讨论】:

  • 但是他想使用 Ajax 来做到这一点,也许你应该添加 How to change it to ajax way using json 例如。
  • 谢谢。这涵盖了我需要的答案的 50%。
【解决方案2】:

这种技术称为分页。这是一个可以帮助您进行分页的 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()}");

【讨论】:

  • 正是我所需要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2012-09-12
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多