Jump to content

Recommended Posts

You would do the same as in a database pagination script, except the total number of rows is the count of your array entries, and instead of making a LIMIT clause in a query to define which rows are retrieved and displayed, you calculate the starting and ending array indexes.

 

Simple pagination script, modified to use an array as the data source -

 

<?php
// pagination from db -> array

$arr = range(1,32); // simulate data (index starts at 0)

$rows_per_page = 15;

// get total number of rows
/*
$query = "SELECT count(*) FROM table WHERE ...";
$result = mysql_query($query, $db);
list($numrows) = mysql_fetch_row($result);
*/
$numrows = count($arr);

// Calculate number of $lastpage
$lastpage = ceil($numrows/$rows_per_page);

// condition inputs/set default
if (isset($_GET['pageno'])) {
   $pageno = $_GET['pageno'];
} else {
   $pageno = 1;
}

// validate/limit requested $pageno
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
   $pageno = $lastpage;
}
if ($pageno < 1) {
   $pageno = 1;
}

// Find start and end array index that corresponds to the reuqeted pageno
$start = ($pageno - 1) * $rows_per_page;
$end = $start + $rows_per_page -1;

// limit $end to highest array index
if($end > $numrows - 1){
$end = $numrows - 1;
}

// database query
/*
$query = "SELECT * FROM table $limit";
$result = mysql_query($query, $db);
//... process contents of $result ...
*/

// display array from $start to $end
for($i = $start;$i <= $end;$i++){
echo $arr[$i] . '<br />';
}
echo "<br />";

// first/prev pagination hyperlinks
if ($pageno == 1) {
   echo " FIRST PREV ";
} else {
   echo " <a href='?pageno=1'>FIRST</a> ";
   $prevpage = $pageno-1;
   echo " <a href='?pageno=$prevpage'>PREV</a> ";
}

// Display current page or pages
echo " ( Page $pageno of $lastpage ) ";

// next/last pagination hyperlinks
if ($pageno == $lastpage) {
   echo " NEXT LAST ";
} else {
   $nextpage = $pageno+1;
   echo " <a href='?pageno=$nextpage'>NEXT</a> ";
   echo " <a href='?pageno=$lastpage'>LAST</a> ";
}
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.