【问题标题】:Php pagination for basic cms基本cms的php分页
【发布时间】:2015-03-31 02:06:00
【问题描述】:


我有分页问题,​​我不得不承认我是 php 编程的新手。
我希望,你能告诉我如何对这些代码进行分页。

index.php ,主页功能。

function homepage() {
  $results = array();
  $data = Article::getList( HOMEPAGE_NUM_ARTICLES );
  $results['articles'] = $data['results'];
  $results['totalRows'] = $data['totalRows'];
  $results['pageTitle'] = "Widget News";
  require( TEMPLATE_PATH . "/homepage.php" );
}



Article.php 获取文章功能

public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS<br> publicationDate FROM articles
            ORDER BY " .$order. " LIMIT :numRows";

 $st = $conn->prepare( $sql );
  $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
  $st->execute();
  $list = array();

    while ( $row = $st->fetch() ) {
      $article = new Article( $row );
      $list[] = $article;
    }



index.php 显示文章 foreach

<?php foreach ($results['articles'] as $article){?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F',$article->publicationDate)?></span>
<a href=".?action=viewArticle&amp;articleId=<?php echo $article->id?>">
<?php echo htmlspecialchars($article->title)?>
</a>
</h2>
<p class="summary"><?php echo htmlspecialchars($article->summary)?></p>
</li>
<?php }?>


谢谢。

【问题讨论】:

    标签: php pdo pagination


    【解决方案1】:

    你需要在 MySql 字符串中使用OFFSET

    $page = isset($_GET['page']) ? $_GET['page'] : 1;
    $itemsPerPage = 10;
    $offset = ($page * $itemsPerPage) - $itemsPerPage;
    
    $sql = "SELECT * FROM articles OFFSET {$offset} LIMIT {$itemsPerPage}";
    

    同时从您的代码中删除 &lt;br&gt;。它只对 HTML 有效,其他地方会报错。


    最终函数(开始)如下所示:

    public static function getList($numRows = 10, $order = "publicationDate DESC") {
    $conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
    $page = isset($_GET['page']) ? $_GET['page'] : 1;
    $order = preg_replace("/[^a-zA-Z\s]/", '', $order);
    $numRows = intval($numROws);
    $offset = ($page * $numRows) - $numRows;
    $sql = "SELECT
              SQL_CALC_FOUND_ROWS *,
              UNIX_TIMESTAMP(`publicationDate`) AS 'publicationDate'
           FROM `articles`
           ORDER BY {$order}
           LIMIT :numRows
           OFFSET :offset";
    
    $st = $conn->prepare( $sql );
    $st->execute(array(':numRows' => $numRows, ':offset' => $pffset));
    

    【讨论】:

    • 我已经删除了&lt;br&gt;,我怎样才能用你的更新我的代码?另外我怎样才能像 1,2,3,4,5 那样进行分页
    • @AlpÖzkan 分页只是与不同的&amp;page=# 参数链接。
    • 谢谢你的努力,你解决了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2019-09-12
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 2011-12-16
    • 2023-03-20
    相关资源
    最近更新 更多