$host = 'localhost'; $user = 'root'; $password = ''; $dbname = 'test'; $per = 5; if(preg_match("/^[1-9][0-9]*$/", $_GET["page"])){ $page = $_GET["page"]; } else { $page = 1; } error_reporting(E_ALL & E_NOTICE); try{ $dbh = new PDO( "mysql:host=" . $host . ";dbname=" . $dbname, $user, $password ); } catch (PDOException $e) { echo $e->getMessage(); exit; } $offset = $per * ($page - 1); $sql = "select * from comments limit " . $offset . "," . $per; $comments = array(); foreach($dbh->query($sql) as $row){ array_push($comments, $row); } $total = $dbh->query("select count(*) from comments")->fetchColumn(); $totalPages = ceil($total / $per); $from = $offset + 1; if($offset + $per < $total){ $to = $offset + $per; } else { $to = $total; }