קוד PHP לדפדוף בין דפי תוכן באתר (pagination)
במקרים רבים יש צורך בדפדוף בין דפים. במדריך זה אציג ואסביר דפדוף באמצעות קוד PHP פשוט. כדי לצפות בקוד בפעולה לחצו על הכפתור:
פונקציה לדפדוף בין מספר גדול של דפים
הפונקציה הבאה מאפשרת להציג רק חלק מהקישורים והיא טובה במיוחד באותם המקרים שמספר הדפים גדול.

הפרמטרים שמועברים לפונקציה הם:
- $classUl - הקלאס של האלמנט שמכיל את הדפדוף.
- $links - מספר הקישורים שיוצגו בדיפדפוף.
- $currentPage - המספר של הדף הנוכחי.
- $last - מספרו של הדף האחרון.
function getPagination($classUl='pagination pagination-lg',$links=4,$currentPage=1,$last)
{
// Prevent linking outside the range
$currentPage = ((int)$currentPage > 0 && (int)$currentPage <= $last)? (int)$currentPage : 1;
// First link
$start = ( ( $currentPage - $links ) > 0 ) ? $currentPage - $links : 1;
// Last link
$end = ( ( $currentPage + $links ) < $last ) ? $currentPage + $links : $last;
// html
$build = '';
$build .= '<ul class="'.$classUl.'">';
$class = ( $currentPage == 1 ) ? "disabled" : "";
$build .= '<li class="' . $class . '"><a href="?page=' . ( $currentPage - 1 ) . '">«</a></li>';
if ( $start > 1 )
{
$build .= '<li><a href="?page=1">1</a></li>';
$build .= '<li class="disabled"><span>...</span></li>';
}
for ( $x = $start ; $x <= $end; $x++ )
{
$class = ( $currentPage == $x ) ? "active" : "";
$build .= '<li class="' . $class . '"><a href="?page=' . $x . '">' . $x . '</a></li>';
}
if ( $end < $last )
{
$build .= '<li class="disabled"><span>...</span></li>';
$build .= '<li><a href="?page=' . $last . '">' . $last . '</a></li>';
}
$class = ( $currentPage == $last ) ? "disabled" : "";
$build .= '<li class="' . $class . '"><a href="?page=' . ( $currentPage + 1 ) . '">»</a></li>';
$build .= '</ul>';
return $build;
}
הקלאס של הדיפדוף "pagination pagination-lg" שייך לפריימוורק Bootstrap
הקוד הבא משמש לבדיקת הקוד. מספרו הנוכחי של הדף נקלט מה-url באמצעות $_GET['page']
$pages = [
'item 1', 'item 2', 'item 3',
'item 4', 'item 5', 'item 6',
'item 7', 'item 8', 'item 9',
'item 10', 'item 11', 'item 12'
];
$numPages = count($pages);
$currentPage = isset($_GET['page'])? (int)$_GET['page'] : 1;
$numLinks = 4;
$class = 'pagination pagination-lg';
echo getPagination($class, $numLinks, $currentPage, $numPages);
אהבתם? לא אהבתם? דרגו!
0 הצבעות, ממוצע 0 מתוך 5 כוכבים
גיא בתאריך: 23.08.2018
תודה רבה. איפה ממקמים את התוכן עצמו? לדוגמא, אני רוצה לרוץ על מערך של מאמרים. איפה אני ממקם את המערך והקריאה למסד הנתונים?