0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPを使ったページネーション(ページング)を習得したので記録しておく

Last updated at Posted at 2020-07-21

PHPを使った恐らく1番簡単なページネーション(ページング)を習得したので記録しておく

今回は複数の画像を表示することを想定。
一部分を抜き出してきたためやや分かりにくいがメモ程度に。
$_GET取得です。
デザインしやすいようリストを使用。

  //ページネーション設定
  $perPage = 6;//最大表示画像数
  $imgs = count($img);//画像数をカウント
  $maxPage = ceil($imgs / $perPage);
  
  if (!isset($_GET['page'])){
    $page = 1;
  } else {
    $page = (int)$_GET['page'];
  }
 
  $startNo = ($page - 1) * $perPage;
  $img = array_slice($img, $startNo, $perPage, true);


  //ページネーション表示
  if ($page > 1) {//最初以外のページにいる場合は最初のページをリンク表示
    print('<li><a href="./index.php?page=1"><< first</a></li>');
  } else if($page == 1){//最初のページにいる場合は表示しない
    print('');
  }
 //全ページをリンク表示
  for ($i = 1; $i <= $maxPage; $i++) {
    if ($i == $page) {//閲覧中のページはリンクなし
      print('<li>'.$i.'</li>');
    } else {//それ以外のページはそのページへのリンクを貼る
      print('<li><a href="./index.php?page='.$i.'">'.$i.'</a></li>');
    }
  }

  if ($page < $maxPage) {//最後以外のページにいる場合は最後のページをリンク表示
    print('<li><a href="./index.php?page='.$maxPage.'">last >></a></li>');
  } else if($page == $maxPage){//最後のページにいる場合は表示しない
    print('');
  }

CSS部分はこんな感じで中央寄せのページネーション。


a{
  color: yellow;
  text-decoration: none;
}

li{
  color: white;
  list-style: none;
  text-align: center;
  padding: 16px;
  display: inline-block;
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?