I think you're asking about 'pagination' - you might want to search the forum for that term.
I have a paginate() function that I use a lot ...
<?php
function paginate($SELECT, $SQL, $PAGE, $ROWS_PER_PAGE){
// First get the total number of rows returned by the query
$mysql_result = mysql_query('SELECT COUNT(*) '.$SQL);
$row = mysql_fetch_row($mysql_result);
$num_rows = $row[0];
// Now calculate the number of pages
$num_pages = ceil($num_rows/$ROWS_PER_PAGE);
// Fix, if necessary, the current page
$cur_page = max(0, min($PAGE - 1, $num_pages - 1));
// Get the next/prev pages, if they exist
$prev_page = max(0, min($cur_page - 1, $num_pages - 1));
$next_page = max(0, min($cur_page + 1, $num_pages - 1));
// Now get the actual page of rows
$mysql_result = mysql_query('SELECT '.$SELECT.' '.$SQL.' LIMIT '.($cur_page*$ROWS_PER_PAGE).','.$ROWS_PER_PAGE);
$results = array();
while($assoc = mysql_fetch_assoc($mysql_result)){
$results[] = $assoc;
}
// Return the lot
return array(
'results' => $results
, 'num_pages' => $num_pages
, 'prev_page' => $prev_page + 1
, 'cur_page' => $cur_page + 1
, 'next_page' => $next_page + 1
, 'last_page' => $num_pages - 1
);
}
?>
An example of how you might use it is:
<?php
require_once('db.php'); // Just connects to the db
// Pluck the get var 'page'
$GLOBALS['CURRENT_PAGE'] = empty($_GET['page'])? 1: $_GET['page'];
$SELECT = '*';
$SQL = 'FROM `element` ORDER BY `atomic_number`';
$ROWS_PER_PAGE = 15;
$PAGE_DATA = paginate($SELECT, $SQL, $GLOBALS['CURRENT_PAGE'], $ROWS_PER_PAGE);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Elements</title>
</head>
<body>
<table border="1" cellpadding="5">
<tr>
<td><a href="<?php echo $_SERVER['PHP_SELF'].'?page=1'; ?>">First page</a><br/><a href="<?php echo $_SERVER['PHP_SELF'].'?page='.$PAGE_DATA['prev_page']; ?>">Previous page</a></td>
<th>Page <?php echo $PAGE_DATA['cur_page']; ?></th>
<td align="right"><a href="<?php echo $_SERVER['PHP_SELF'].'?page='.$PAGE_DATA['next_page']; ?>">Next page</a><br/><a href="<?php echo $_SERVER['PHP_SELF'].'?page='.$PAGE_DATA['last_page']; ?>">Last page</a></td>
</tr>
<tr><th>Atomic number</th><th>Chemical symbol</th><th>Name</th></tr>
<?php
// Might be less than $ROWS_PER_PAGE
$ROW_COUNT = count($PAGE_DATA['results']);
for($i = 0; $i < $ROW_COUNT; $i++){
$row = $PAGE_DATA['results'][$i];
?>
<tr><td><?php echo $row['atomic_number']; ?></td><td><?php echo $row['chemical_symbol']; ?></td><td><?php echo $row['name']; ?></td></tr>
<?php
}
?>
</table>
</body>
</html>
To see it in action: http://www.pntestbed.co.uk/test/paginate/
Hope that helps.
P.