Hello,

I am so close on this one. I just need a tiny weenie bit of input from a clever PHP developer and I can do the rest.

I have a site that returns data from a txt file. The problem is that there is so much of this data that I need it to be paginated. I have two php files that do both of these functions perfectly, but my problem is combining them.

I have created a .txt file that I am using as a Flat File Database. I specified that it is | deliminated (however, I am only using one value separated by line breaks, so there aren't acctually any |'s in the .txt file). Here is an extract of flatfiledatabase.txt

<!-- Comment1 --><div class="class"><a href="http://www.url.com/1" target="blank"><img src="http://www.url.com/image1.jpg" border="0"></a></div>
<!-- Comment2 --><div class="class"><a href="http://www.url.com/2" target="
blank"><img src="http://www.url.com/image2.jpg" border="0"></a></div>
<!-- Comment3 --><div class="class"><a href="http://www.url.com/3" target="blank"><img src="http://www.url.com/image3.jpg" border="0"></a></div>
<!-- Comment4 --><div class="class"><a href="http://www.url.com/4" target="
blank"><img src="http://www.url.com/image4.jpg" border="0"></a></div>
...

You get the idea.

I have found a code that will load this database and echo all of this html (using a simple loop) to a browser and it works like a treat.

<?php

/* Open the file */
$fp = fopen('flatfiledatabase.txt','r');
if (!$fp) {echo 'Error: Unable to open txt file.'; exit;}

/* Loop started to read the txt file to the end */
while (!feof($fp)) {
$line = fgets($fp, 1024);
list ($fp) = split ('\|', $line);

echo ''.$fp.'';

/* 'file pointer' incremented by one, so the loop will start reading from the next line of the database. */
$fp++;

/* End the loop */
}

/* Close the file */
fclose($fp);

?>

This returns the entire database to one page. The problem I face is that I need this data to be paginated.

I have found the following PHP code on the web that illustrates exactly what I need.

<? $data = array(
  1 => array('user' => 'Bob', 'comment' => 'I like your site!'),
  2 => array('user' => 'George', 'comment' => 'I like your site more than he does!'),
  3 => array('user' => 'Tom', 'comment' => 'I like your site, but mine\'s better.'),
  4 => array('user' => 'Alex', 'comment' => 'This site is awful. Mine is MUCH better.'),
  5 => array('user' => 'Admin', 'comment' => 'Stop insulting  month!!!'),
  6 => array('user' => 'Harry', 'comment' => 'Woof!'),
);
$perpage = 2; //Obviously you would want to change this to something higher, depending on the content.
if(isset($_GET['start'])) $start = $_GET['start']; else $start = 0;
$numposts = count($data);
$data = array_slice($data, $start, $perpage);

foreach($data as $k => $v)
{
  echo $data[$k]['user'].' said: '.$data[$k]['comment'].'<br/>'."\n";
}
if($start > 0)
{
	$text .= '<a href="index.html?start='.($start - $perpage).'">< Previous Page </a>';
}
if($start > 0 && $numposts > $perpage && $start < $numposts - $perpage)
{
	$text .= ' | ';
}
if($numposts > $perpage && $start < $numposts - $perpage)
{
	$text .= '<a href="index.html?start='.($start + $perpage).'">Next Page ></a>';
}
echo $text;

?>

This code works perfectly too. So all I need to do is implement the paginated viewing illustrated in this PHP file to the loading functionality of the first PHP file.

Any ideas are much appreciated.

Merry Christmas & A Happy New Year,
David Apple

    file() will read the file in to an array that you can them use in the pagination script. Since your using a single dimensional array, and the script above expects a multi-demisonal one, there's some work to be done.

    I assume you know it would be a lot easier using a 'real' database.

      Oh dear.

      I'm using a txt file because it makes the horrendous workflow prior to that so much quicker, and allows for heaps of automation.

      So if I use file() instead of fopen() then it should pull the data to be paginated.. so the very first line would read..

      $data = file('flatfiledatabase.txt');

      Is this right? You said that I need to adapt the pagination script from a multi-dimensional array to a single dimensional one. Sure this is easier than doing it the other way around, no?

      Do you have any more tips or advice because I'm really eager to get this in the bag. Just wish a knew more PHP.

      Dave

        if its 'so much quicker' then why you need to ask?

        solve it with a real database, that is so much quicker.

        In flatfiledatabase.txt you need to convert the special characters into its htmlentities to protect the flat-file from code injection and replace the separator character. What if my username is: |name| ?

        This file is gettint robust, on evry page refresh you need to open the whole contents.

        once you opened this file,

        $data=file("database.txt");

        you have to call foreach to apply the explode() on each rows to be able to build the multy dimensional version.

          OK. I see what you mean. Perhaps I do need a database.

          Do you know if it's possible to convert my txt file into a database without using MySQL or any other database system that I will have to pay extra for? So, could I carry on using my txt file, but fill it with data that would be read as if it were a database?

          Could I do this to my txt file?..

          array('<!-- Comment1 --><div class="class"><a href="http://www.url.com/1" target="_blank"><img src="http://www.url.com/image1.jpg" border="0"></a></div>'),
          array('<!-- Comment2 --><div class="class"><a href="http://www.url.com/2" target="_blank"><img src="http://www.url.com/image2.jpg" border="0"></a></div>'),
          array('<!-- Comment3 --><div class="class"><a href="http://www.url.com/3" target="_blank"><img src="http://www.url.com/image3.jpg" border="0"></a></div>'),
          array('<!-- Comment4 --><div class="class"><a href="http://www.url.com/4" target="_blank"><img src="http://www.url.com/image4.jpg" border="0"></a></div>'),
          ... 
          

          Or is this impossible?

            there is alternate ways, like sqlite.

            It has LIMIT and OFFSET features if you want to use a pager.

            here is an example:

            // create new database (procedural interface)
            $db = sqlite_open("valami.sqlite")  ;
            /*
             sqlite_query($db , "CREATE TABLE chat
             (
             id INTEGER PRIMARY KEY, name CHAR(255), Comment TEXT(500) )");
            

            echo the query:

            // execute query
            $result = sqlite_query($db, "SELECT * FROM chat LIMIT 0,1"); // apply a pager here
            // iterate through the retrieved rows
            while ($row = sqlite_fetch_array($result,SQLITE_ASSOC )) {
                echo 'Name: ' . $row['name'] ."<br/>";
                echo 'Commant: ' . $row['Comment'] ."<br/>";
            }
            

            Insert code:

            $name=sqlite_escape_string($_POST["name"]);
            $Comment=sqlite_escape_string($_POST["Comment"]);
            sqlite_query($db, "INSERT INTO chat (name,Comment) VALUES ('$name','$Comment')");
            

            Updater OR delete code:

            $name=sqlite_escape_string($_POST["name"]);
            $Comment=sqlite_escape_string($_POST["Comment"]);
                    $id= sqlite_escape_string($_POST["hidden"]);
            
                if(!empty($_POST["del"]))
                $sql="DELETE FROM chat WHERE id='$id'";
                else
                $sql="UPDATE chat SET name='$name',Comment='$Comment'  WHERE id='$id'";
            
                sqlite_query($db, $sql) or die(sqlite_last_error() . " , error in query:". $sql);
            

            You can generate basic code for sqlite, here:
            sql lite code generator 🙂

              My head hurts :queasy: Can I implement SQLite without having to pay my service provider more money?

              A lot of this SQL stuff goes right over my head. I would love to be able to understand it more. I've had the dummies guide to SQL for the past couple of years but every time i read it, I glaze over and stop understanding.

              I've installed a PHPBB forum before but that's all automated so I didn't need to get down and dirty with SQL.

              I think I might have to consed one this one and just pull the txt file without implementing pagination. I think you're right, the only way to do this properly is using SQL and it's just to costly and difficult.

              Thanks for all of your help.

                Actually, just before I give up on this. I was thinking about what you said earlier...

                djjjozsi;10937929 wrote:

                In flatfiledatabase.txt you need to convert the special characters into its htmlentities to protect the flat-file from code injection and replace the separator character. What if my username is: |name| ?

                This file is gettint robust, on evry page refresh you need to open the whole contents.

                you have to call foreach to apply the explode() on each rows to be able to build the multy dimensional version.

                Loading the txt file for every page refresh isn't too much of a problem because it's only going to be 100kb or so max. Also, the | deliminator is never going to appear in a variable and I have solved all of the problems with escaping quotes and other characters.

                So, how is there a way of converting the txt file in to an array and using foreach() and explode()? I have found this tutorial http://www.homeandlearn.co.uk/php/php10p7.html but I'm a little fuzzy on exactly how to apply it to my code.

                Any ideas? or should I knock it on the head?

                  Hey, I've just had a breakthrough with trying to convert the txt file to an array and then use explode() 🆒

                  <?php
                  $file_handle = fopen('flat-file-data.txt', 'r');
                  if (!$file_handle) {echo 'ERROR'; exit;}
                  
                  /* Start Loop */
                  while (!feof($file_handle)) {
                  
                  $line_of_text = fgets($file_handle, 2048);
                  $parts = explode('\|', $line_of_text);
                  
                  echo $parts[0]. ' ';
                  
                  $file_handle++;
                  
                  }
                  fclose($file_handle);
                  
                  ?>

                  However, this is a little bit glitchy. The occasional one or two images do not load but %98 of it works beautifully. Any ideas on how to make it more stable?

                  Also, how do I go about applying pagination to this now that I have a set of arrays?

                  Dave

                    Can I implement SQLite without having to pay my service provider more money?

                    You may ask your HOST's support team about SQL lite (its usually a free stuff).

                    one or two images do not load but %98 of it works beautifully. Any ideas on how to make it more stable?

                    Before you create the image tags to make the images
                    visible check the file existence.

                    Can you post here a sample from your text file?

                    $file=file("textfile.txt");
                    foreach($file AS $row)
                    {
                    $columns=explode("|",$row);
                    echo $columns[0]  . " -  ". $columns[1] . "<br />";
                    }
                      Write a Reply...