PHP MYSQL

SIMPLE PAGINATION WITH PHP MYSQL

(quick guide & example)

$pdo = new PDO("mysql:host=HOST; dbname=NAME;charset=utf8", USER, PASS);

CONNECT TO DATABASE

01

ENTRIES PER PAGE define("PER_PAGE", 10);

CALCULATE TOTAL PAGES

02

TOTAL NUMBER OF PAGES $stmt = $pdo->prepare("SELECT CEILING(COUNT(*) / PER_PAGE") FROM `TABLE`"); $stmt->execute(); $total = $stmt->fetchColumn();

LIMIT X, Y $now = isset($_GET["p"]) ? $_GET["p"] : 1 ; $x = ($now - 1) * PER_PAGE; $y = PER_PAGE;

SQL FETCH $stmt = $pdo->prepare("SELECT * FROM `TABLE` LIMIT $x, $y"); $stmt->execute(); $data = $stmt->fetchAll();

GET CURRENT PAGE ENTRIES

03

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

DRAW PAGINATION for ($i=1; $i<=$total; $i++) {   echo "<a ref='SCRIPT.PHP?p=$i>$i</a>"; }

DRAW HTML LIST & PAGE

04