V
V
Vladimir Vedernikov2020-05-06 14:59:36
PHP
Vladimir Vedernikov, 2020-05-06 14:59:36

How to implement pagination in a script?

Good day. The essence of the issue is that I can not implement pagination in the script. There is a script that displays either all the articles on the page from the news table (at the address /?do=news) or only those belonging to a specific category when going to (/?do=news&categoryId=5)
I read a lot of articles but could not integrate into this one script. That's why I ask you for help. The function itself

public static function getCategory( $numRows=1000000, $categoryId=null ) {
        
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $categoryClause = $categoryId ? "WHERE categoryId = :categoryId" : "";
    $sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate
            FROM news $categoryClause
            ORDER BY id DESC LIMIT :numRows";

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

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

    // Now get the total number of articles that matched the criteria
    $sql = "SELECT FOUND_ROWS() AS totalRows";
    $totalRows = $conn->query( $sql )->fetch();
    $conn = null;
    return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
  }


Thanks in advance)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2020-05-06
@ProWebZ

public static function getCategory($categoryId = null, $offset = 0, $count = 1000 ) 
{
    ...
    $sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate
            FROM news $categoryClause
            ORDER BY id DESC LIMIT :offset, :count";
   ...
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question