PHP MYSQL

PAGINATION WITH PHP MYSQL

$pdo = new PDO(   "mysql:host=DB_HOST;".   "dbname=DB_NAME;".   "charset=utf8",   DB_USER, DB_PASSWORD, [     PDO::ATTR_ERRMODE =>     PDO::ERRMODE_EXCEPTION,     PDO::ATTR_DEFAULT_FETCH_MODE     => PDO::FETCH_ASSOC ]);

CONNECT TO DATABASE

01

$stmt = $pdo->prepare("SELECT CEILING(COUNT(*) / PER_PAGE") `pages` FROM `TABLE`"); $stmt->execute(); $pageTotal = $stmt->fetchColumn();

CALCULATE TOTAL PAGES

02

CALCULATE LIMIT X, Y $pageNow = isset($_GET['page']) ? $_GET['page'] : 1 ; $limX = ($pageNow - 1) * PER_PAGE; $limY = PER_PAGE;

SQL FETCH $stmt = $pdo->prepare("SELECT * FROM `TABLE` LIMIT $limX, $limY"); $stmt->execute(); $entries = $stmt->fetchAll();

GET CURRENT PAGE ENTRIES

03

DRAW ENTRIES <ul><?php foreach ($entries as $e) {    echo "<li>$e</li>; } ?></ul>

DRAW PAGINATION for ($i=1; $i<=$pageTotal; $i++) {   echo "<a ref='script.php?page=$i"; }

DRAW HTML LIST & PAGE

04