PHP MySQLからデータを引いて、ページング

<?php

define('DB_HOST', 'localhost');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'xxxx');
define('DB_NAME', 'testdb');
define('COMMENTS_PER_PAGE', 5);

if (preg_match('/^&#91;1-9&#93;&#91;0-9&#93;*$/', $_GET&#91;'page'&#93;)){
$page = (int)$_GET&#91;'page'&#93;;
} else {
  $page = 1;
}

error_reporting(E_ALL & ~E_NOTICE);

try {
  $dbh = new PDO
('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASSWORD);
} catch (PDOException $e){
  echo $e->getMessage();
  exit;
}

// select * from comments limit OFFSET,Count
// page offset Count
// 1 0 5
// 2 5 5
// 3 10 5

$offset = COMMENTS_PER_PAGE * ($page -1);
$sql = "select * from comments limit ".$offset.",".COMMENTS_PER_PAGE;
$comments = array();
foreach ($dbh->query($sql) as $row){
 array_push($comments, $row);
}
$total = $dbh->query("select count(*) from comments")->fetchColumn();
$totalPages = ceil($total / COMMENTS_PER_PAGE);

$from = $offset + 1;
$to = ($offset + COMMENTS_PER_PAGE) <  $total ? ($offset + COMMENTS_PER_PAGE): $total;

?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>コメント一覧</title>
</head>
<body>
    <h1>コメント一覧</h1>
    <p>全<?php echo $total; ?>件中、<?php echo $from; ?>件~<?php echo $to; ?>件を表示しています</p>
    <ul>
    <?php foreach ($comments as $comment) : ?>
      <li><?php echo htmlspecialchars($comment&#91;'comment'&#93;,ENT_QUOTES,'UTF-8'); ?></li>
    <?php endforeach; ?>
  </ul>
  <?php if($page > 1) : ?>
  <a href="?page=<?php echo $page-1; ?>">前へ</a>
<?php endif; ?>
  <?php for ($i = 1; $i <= $totalPages; $i++): ?>
    <?php if ($page == $i) : ?>
  <strong><a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a></strong>
<?php else: ?>
    <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
<?php endif; ?>
  <?php endfor; ?>
  <?php if ($page < $totalPages): ?>
  <a href="?page=<?php echo $page+1; ?>">次へ</a>
<?php endif; ?>
</body>
</html>

SQLでデータを作ります。

create database testdb;
grant all on testdb.* to dbuser@localhost identified by 'xxxx';
use dotinstall_paging_php

create table comments (
 id int not null auto_increment primary key,
 comment text,
 created datetime,
 modified datetime
);

insert into comments (comment, created, modified) values
('コメント1', now(), now()),
('コメント2', now(), now()),
('コメント3', now(), now()),
('コメント4', now(), now()),
('コメント5', now(), now()),
('コメント6', now(), now()),
('コメント7', now(), now()),
('コメント8', now(), now()),
('コメント9', now(), now()),
('コメント10', now(), now()),
('コメント11', now(), now()),
('コメント12', now(), now()),
('コメント13', now(), now()),
('コメント14', now(), now()),
('コメント15', now(), now()),
('コメント16', now(), now()),
('コメント17', now(), now()),
('コメント18', now(), now());

%e7%84%a1%e9%a1%8c