View Single Post
Old 01-01-2010, 07:13 PM   #4 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

I would like to introduce another approach to your problem, one which you're probably not aware of so would've have considered yet. To so do, you will have to think a little out of the box and if you're new to using classes/objects then things might seem a bit weird.

Another concept in there is filtering user input using the filter extension. It just makes the common task of filtering input a bit easier by allowing us to quickly validate the input type (in this case, integers only) and optionally limit the values to a specific range (1…1000) or specify a default value if none is present (1).


PHP Code:
// Open our flat file database for reading
$lines = new SplFileObject('flat-file-data.txt''r');

// Grab the user-requested page number from $_GET (with max/min/default limits)
$page    filter_input(INPUT_GET'page'FILTER_VALIDATE_INT, array(
    
'options' => array(
        
'default'   => 1,
        
'max_range' => 1000,
        
'min_range' => 1
    
)
));

// Ten lines per page
$perpage 10;

// How many lines into the file should we start at
$offset  = ($page 1) * $perpage;

// Limit the lines to the start point and number of lines per page
$page    = new LimitIterator($lines$offset$perpage);

// If this page does not exist (offset is too big), show first page instead
if (iterator_count($page) === 0) {
    
$page = new LimitIterator($lines0$perpage);
}

// Loop over this page of lines, displaying each one
foreach ($page as $line) {
    echo 
$line;

P.S. The LimitIterator isn't documented beyond the basic method and arguments lists. If you have any questions, do ask me... they might be useful for when I get around to writing the documentation for that class.
Salathe is offline  
Reply With Quote