>데이터 베이스 >MySQL 튜토리얼 >PHP에서 간단한 데이터베이스 페이지 매김을 구현하는 방법은 무엇입니까?

PHP에서 간단한 데이터베이스 페이지 매김을 구현하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2025-01-21 19:07:10238검색
<code class="language-php"><?php
// Database connection (replace with your credentials)
$host = 'localhost';
$dbname = 'your_database';
$user = 'your_user';
$password = 'your_password';

try {
    $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}


// Get total number of records
$stmt = $dbh->query('SELECT COUNT(*) FROM your_table');
$totalRecords = $stmt->fetchColumn();


// Pagination settings
$recordsPerPage = 20;
$totalPages = ceil($totalRecords / $recordsPerPage);
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, min($currentPage, $totalPages)); // Ensure page number is within valid range

$offset = ($currentPage - 1) * $recordsPerPage;


// Fetch data for current page
$stmt = $dbh->prepare("SELECT * FROM your_table LIMIT :limit OFFSET :offset");
$stmt->bindParam(':limit', $recordsPerPage, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);


// Display data
echo "<h2>Data (Page " . $currentPage . " of " . $totalPages . ")</h2>";
if ($data) {
    echo "<ul>";
    foreach ($data as $row) {
        echo "<li>" . implode(", ", $row) . "</li>"; // Adjust as needed for your table structure
    }
    echo "</ul>";
} else {
    echo "<p>No data found for this page.</p>";
}



// Display pagination links
echo "<div class='pagination'>";
for ($i = 1; $i <= $totalPages; $i++) {
    $activeClass = ($i == $currentPage) ? 'active' : '';
    echo "<a href='?page=" . $i . "' class='" . $activeClass . "'>" . $i . "</a>";
}
echo "</div>";


?>

<!DOCTYPE html>
<html>
<head>
<title>Simple Pagination</title>
<style>
.pagination a {
    display: inline-block;
    padding: 8px 12px;
    margin: 0 4px;
    text-decoration: none;
    border: 1px solid #ccc;
}

.pagination a.active {
    background-color: #4CAF50;
    color: white;
}
</style>
</head>
<body>
</body>
</html>
</code>

How to Implement Simple Database Pagination in PHP?

이 개선된 예에는 다음이 포함됩니다.

  • 오류 처리: try-catch 블록은 잠재적인 데이터베이스 연결 오류를 처리합니다.
  • Prepared 문: 준비된 문을 사용하여 SQL 주입 취약점을 방지합니다. 이는 보안에 매우 중요합니다.
  • 입력 유효성 검사: 원래 예에서는 filter_input을 사용했지만 포괄적인 유효성 검사가 부족했습니다. 이 버전에서는 페이지 번호가 양의 정수이고 유효한 범위 내에 있는지 확인합니다.
  • 더 명확한 데이터 표시: 데이터가 더 사용자 친화적인 형식(순서가 지정되지 않은 목록)으로 표시됩니다. 데이터베이스 테이블의 열 이름과 일치하도록 implode 부분을 조정해야 합니다.
  • 완전한 HTML: 더 나은 렌더링을 위해 완전한 HTML 구조를 제공합니다.
  • CSS 스타일링: 페이지 매기기 링크 스타일을 지정하기 위한 기본 CSS가 포함되어 있습니다.
  • 자리 표시자 값: "your_database", "your_user", "your_password""your_table"를 실제 데이터베이스 자격 증명 및 테이블 이름으로 바꿔야 합니다.

이 코드를 실행하기 전에 필요한 데이터베이스와 테이블을 생성하는 것을 잊지 마세요. 이 향상된 예제는 PHP의 페이지 매김을 위한 더욱 강력하고 안전한 솔루션을 제공합니다.

위 내용은 PHP에서 간단한 데이터베이스 페이지 매김을 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.