[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 443
  • Last Modified:

CSV - Display Values

I'm trying to make a php script to output a csv file.

What I'd like to happen is to have a max of 10 results per page, and a next page previous page option.

This is the code I've got so far, it may be simpler to just start again I don't mind either away. Just as long as the list is split into the same elements.


$filename = "example.csv";

$id = fopen($filename, "r"); //open the file
while ($data = fgetcsv($id, filesize($filename))) //start a loop
$table[] = $data;
fclose($id); //close file

echo "<table>\n";

foreach($table as $row)
echo "<tr>";
   foreach($row as $data)
      list ($key_number, $title, $sub_title, $category, $extra, $x, $y) = $line;

   echo "<td>$key_number</td><td>$title</td>";
echo "</tr>\n";

echo "</table>\n";

  • 2
1 Solution
You want your first foreach loop to count the rows it has 'seen'. If your page starts at the, say, 'pagestart'th row, it should ignore the first 'pagestart' rows, print 10 rows following the 'pagestart'th row, then quit.

'pagestart' will be a parameter, probably received using the GET method, with a default of 0. Your 'next' link should point to itself with pagestart=pagestart+10 and the 'previous' link with pagestart=pagestart-10. Here is a quick and dirty example:

$pagestart = $_GET['pagestart'];

$i = 0;
foreach($table as $row)
    if ($i >= $pagestart) {
        /* print the row */

    if ($i >= $pagestart + 10)

    $i = $i + 1;

echo "<a href=\"me.php?pagestart=".$pagestart-10."\">previous</a>\n";
echo "<a href=\"me.php?pagestart=".$pagestart+10."\">next</a>\n";
$i could be renamed to '$currentrow' to make the code more readable.
ncooAuthor Commented:
That doesn't really work.  That's why it may be best to start the code from the begining, if I explain the problem fully hopefully it will help.

I've got a CSV file, I want to display this with 10 results per page.  Idealy I'd like the next tag and previous tag to only appear when need, I.e. so the previous tag doesn't appear at the start of the file, I'd also like some page numbers at the bottom to help skip through the file (I don't know if you've herd of pager.php but this covers this part of the script but I've never worked out how to use it correctly).

I hope that explains the problem better.
Marcus BointonCommented:
You might like to try the PEAR pagers instead. The documentation on them is quite good, and it automatically deals with making irrelevant links disappear.


Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now