Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pagination with flatfile database

Status
Not open for further replies.

PhoenixDown

Programmer
Jul 2, 2001
279
0
0
CA
I have a flat file database delimited with |. Can someone please help me a code which can do the pagination? Let's say max is 10 per page.

My DB is set up like the following:

test|test|test
test2|test2|test2
test3|test3|test3

Thanks alot!

-Calvin

 
i'd use fgetcsv() to read in the file line by line (specify the delimiter) for up to 10 lines.

in the link to the next page pass an offset variable that you can use to determine the startpoint. because it is a flatfile, you will need to read through the file from the beginning, but just don't do anything with the input until you get to the relevant row.

e.g
Code:
$filename = ""; //full path to filename
$pagelength = 10; //change this var for longer pages
if (isset($_GET['offset'])) //note that you should do some checking here to make sure the variable is clean
{
  $offset = $_GET['offset'];  
  $newoffset = $offset + $pagelength;
}
else
{
  $offset = 0; 
  $newoffset = $offset + $pagelength;
}
if (!file_exists($filename))
  { die ("database does not exist");}
//database exists
$fh = fopen ($filename, "r");  //the r mode is read only, pointer at the start of the file

while ($data = fgetcsv ($fh, 1024, "|")) // this line does most of the hard work. if you need longer than 1024 chars per line then increase the middle numeral [or use a proper database...]
{ 
   if (count($data) >= $newoffset)
   { 
     break; //exits the while loop
   }

} 
fclose ($fh); 
// you now have $data populated with your db results.
print_r($data);
$newoffset
echo "<p><a href=\"$_SERVER[PHP_SELF]?offset=$newoffset\">Next Page</a></p>";

note that if you want to add some intelligence into the code such that it adds page numbers and knows whether to display a next page link, you will have to read through the whole file each time to calculate the number of rows there are. you will need to restructure the while loop to accommodate this.

hth
Justin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top