Samstag, 13 September 2025

Top 5 diese Woche

Ähnliche Tutorials

Pagination

Dieser Codeschnipsel zeigt, wie man mit Pagination lange Datenbank-Listen in übersichtliche Seiten aufteilt.

<?php
$mysqli = new mysqli("localhost", "root", "", "testdb");
if ($mysqli->connect_error) {
    die("Verbindung fehlgeschlagen: " . $mysqli->connect_error);
}
$limit = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$resultTotal = $mysqli->query("SELECT COUNT(*) AS total FROM users");
$totalRows = $resultTotal->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $limit);
$result = $mysqli->query("SELECT * FROM users ORDER BY id ASC LIMIT $limit OFFSET $offset");
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Pagination</title>
</head>
<body>
<h2>Pagination mit PHP & MySQL</h2>
<table border="1" cellpadding="8" cellspacing="0">
    <tr>
        <th>ID</th>
        <th>Name</th>
    </tr>
    <?php while ($row = $result->fetch_assoc()): ?>
    <tr>
        <td><?= $row['id'] ?></td>
        <td><?= htmlspecialchars($row['name']) ?></td>
    </tr>
    <?php endwhile; ?>
</table>
<div>
    <?php if ($page > 1): ?>
        <a href="?page=<?= $page - 1 ?>">Zurück</a>
    <?php endif; ?>
    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <?php if ($i == $page): ?>
            <strong>[<?= $i ?>]</strong>
        <?php else: ?>
            <a href="?page=<?= $i ?>"><?= $i ?></a>
        <?php endif; ?>
    <?php endfor; ?>
    <?php if ($page < $totalPages): ?>
        <a href="?page=<?= $page + 1 ?>">Weiter</a>
    <?php endif; ?>
</div>
</body>
</html>
Vorheriges Tutorial
Nächstes Tutorial

Hier etwas für dich dabei?