Question

Simple Pagination

Asked by: Eternal_Student

Hi guys,

My php is limited so any help/examples are much appreciated.

I have a directory that holds several images for a section as follows:

/literature/
literature1.jpg
literature2.jpg
literature3.jpg
literature4.jpg
literature5.jpg
literature6.jpg
etc ..

What I want is to display "literature1.jpg" with some "descriptive text" on a page.

So the html output would look like:

<p>Here is the text for the following image</p>
<img src="/images/literature/literature1.jpg" />

Now I want these to all work with the same template. So it will load the first by default and then each image/description will be represented by pagination like so:

1, 2, 3, 4, 5, 6, etc

So each number will change the query in the url.

Any ideas on how best to approach this. I have opted against using a database so it is territory I am unfamiliar with.

Thanks.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-12-10 at 09:33:27ID22088429
Tags

pagination

,

php

,

simple

Topic

PHP Scripting Language

Participating Experts
3
Points
500
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

    Free Tech Articles

    1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
      It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
    2. SCCM OSD Basic troubleshooting
      SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
    3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
      This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
    4. Create a Win7 Gadget
      This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
    5. Outlook continually prompting for username and password
      There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
    6. Backup Exchange 2010 Information Store using Windows Backup
      There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

    Cloud Class Webinars

    1. Avoiding Bugs in Microsoft Access
      Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
    2. Top 10 Best New Features in Visio 2010
      Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
    3. IT Consultant Business Secrets Revealed
      Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
    4. Disaster Recovery and Business Continuity
      Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
    5. Organize Your Visio Diagrams with Containers and Lists
      Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
    6. How to Us Objects, Properties, Events and Methods in Microsoft Access
      Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

    Join the Community

    Give a Little. Get a Lot.

    Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

    Join the Community

    Answers

     

    by: gemdeals395Posted on 2006-12-10 at 12:18:25ID: 18111551

    Wow, without using a database I guess you could rename the image names like so:

    Here_is_the_text_for_the_following_image.jpg

    Then when you read the directory you get the names of the files into variables then alter the text based on the way you named it like in the following we replace underscores with spaces and the up arrao shift+6 with a period. Now by formatting how you name each image you can get the results your after with out a database ;)

    function formatText($image) {
          $text = explode('.', $image);
          $text = str_replace("_", " ", $text[0]);
          $text = str_replace("^", ".", $text);
          $text = ucfirst($text);
          return $text;
    }

    $image = 'here_is_the_text_for_the_following_image^.jpg';
    $text = formatText($image);

    echo("<p>$text</p>");

     

    by: gemdeals395Posted on 2006-12-10 at 12:19:46ID: 18111554

    Also since we are using the command ucfirst() inside the function there is no need to capitolize the first letter of each sentence.

    Enjoy ;)

     

    by: ClickCentricPosted on 2006-12-10 at 12:41:18ID: 18111621

    That could easily violate the filename limitations of many filesystems if the text is longer than a short sentence.  XML or an INI file is the best way to go since php has built in support for them (php5 for XML, php4 for INI)

     

    by: Eternal_StudentPosted on 2006-12-10 at 12:55:04ID: 18111671

    Hi again Click.

    I was looking purely for a php method. Like a switch statment or something?

    Im just unsure how to work out the pagination part really.

     

    by: ClickCentricPosted on 2006-12-10 at 13:15:03ID: 18111748

    A purely php method for what?  To include the text?  Hard-coding the text into a php file is pretty much the worst way you could do it, but if you're intent on doing that, you can simple store it in an array.  

    $items[0] = "some text";
    $items[1] = "some more text";

    etc...

    But I strongly recommend against this.

     

    by: Eternal_StudentPosted on 2006-12-10 at 13:59:06ID: 18111931

    But surely that is exactly what you would be doing with an INI file?

     

    by: ClickCentricPosted on 2006-12-10 at 16:51:06ID: 18112369

    Well, no.  You could have an ini file for each image which would have the attributes for the image (caption, sizes unless they're all the same size and any other information needed for them).  Or you could even include a base64 encoded version of the image in the ini file.  A database is just an alternate method of storage, the concept behind it is still the same even if you go with the filesystem method, so you still should think in the same terms.

     

    by: jk2001Posted on 2006-12-11 at 04:42:24ID: 18114213

    One way you can do it is to have the script in the document root directory, and the ini files (or even php files) in each subdirectory.

    If you opt for php, you can use a format like this for the text.  Name it captions.php:
    <?php
    $caption['literature1.jpg'] = "This is the first caption";
    $caption['literature2.jpg'] = "This is the second caption";
    $caption['literature3.jpg'] = "This is the third caption";
    ...
    ?>

    Then, in the doc root, the script should accept a URL like this:
           /show.php?dir=literature&image=literature1.jpg
    The image parameter should be optional, too.  The script could work like this:

    <?php
    $dir = $_GET['dir'];
    $image = $_GET['image'];

    // validate directory
    if (preg_match("#(\.|/)#", $dir)) die('dots and slashes in dir disallowed');
    if (!is_dir($dir)) die('bad directory');

    include($dir."/captions.php");   // loads in captions

    // load all the images into an array
    $dh = opendir($dir);
    while($d = readdir($dh)) {
      if (!preg_match("#^\.#",$d))  $images[] = $d;
    }

    // if there's no image specified, use a default
    if (!$image) $image=$images[0];

    if (preg_match("#/#", $image)) die('slashes in image disallowed');

    if (!file_exists($image)) die("image does not exist");

    // draw the navigation
    for($i=0; $i < count($images); $i++)
    {
        $img = $images[$i];
        if ($img != $image)
           echo "<a href=?dir=$dir&image=$img>$i</a>";
        else
           echo "$i";
        if ($i < count($images) - 1) echo ", ";
    }
    echo "<img src='$dir/$image'>";
    echo $captions[$image];

    // maybe the images array should be sorted
    ?>

     

    by: ClickCentricPosted on 2006-12-11 at 04:50:10ID: 18114243

    All of this, including my own suggestions, does add overhead, though.  This is basically the reason why database servers exist.  To offload the overhead of the alternative methods onto a system geared primarily towards it.  Also, when all is said and done, the time and effort of coding it in a way that uses the filesystem instead is on the same level of difficulty as that which would have been used to utilize a database. And likely longer as the code to retrieve information from a database for several database systems is already included in php whereas to do it with any filesystem method, you're going to have to cobble together the pieces dependent on the way you store the information.

     

    by: Eternal_StudentPosted on 2006-12-11 at 13:07:07ID: 18117943

    I agree that the database method may be easier, but also slower.

    jk2001,

    Thats a good way of doing it. Is there anyway you can hide the url query in the browser ?

     

    by: Eternal_StudentPosted on 2006-12-11 at 13:55:07ID: 18118417

    Also, I wanted to pre-load the images using Javascript. Is there anyway of adding that to the process?

     

    by: ClickCentricPosted on 2006-12-11 at 16:46:54ID: 18119539

    Well, no...the database method isn't necessarily slower.  It 'can' be slower, but it depends on a number of factors, not least of which is the makeup of the server it's housed on.  With a dedicated server with fast scsi hard drives and a small number in the data set, yes, it can be faster to use the filesystem.  It's likely you're on a shared hosting server where the filesystem of the server is already heavily used.  This can easily shift the balance of speed.  The only way to actually determine that is to test it.  There's no situation in which it's a 'given'.  Traversing directories can also add overhead that can shift the balance.  Every part of the equation counts.  Accessing a file in a subdirectory can often times be slower than accessing a file in a subdirectory.  For permission reasons if nothing else (and it takes as much time to verify the permissions be it set right or wrong).

     

    by: jk2001Posted on 2006-12-11 at 19:56:28ID: 18120172

    Add these two lines to the program, around where the img tag is generated.

    $nextimage = $images[$i+1];
    if ($nextimage) echo "<img src='$dir/$nextimage' width=1 height=1>";

    And adjust your layout so you can hide this image somewhere on the page.

    --------------------------
    Also, I realized that I didn't need to do the directory traversal.  That was extraneous.

    Replace:
    // load all the images into an array
    $dh = opendir($dir);
    while($d = readdir($dh)) {
      if (!preg_match("#^\.#",$d))  $images[] = $d;
    }

    With:

        $images = array_keys($captions);

    I forgot that the filenames are in the caption's keys.
    --------------------------

    As for the DB versus file...  The DB way is usually easier, but there is some overhead in learning it.  The "file" way depends on naming conventions and whatnot, but, on the other hand, most programmers know the filesystem calls anyway (and if they don't, they eventually will).  Performance-wise, it's important to remember that accessing the db on a shared server results in a file-open, unless you're a very busy site.  The DB runs on top of the file system.

    There is an interesting semantic differences between a file hierarchy and sets of tables.  One is a hierarchy, and the other is tabular.  If you want to create a site that has hierarchy and accesses files, you might write less code with the file method.  If you want to simulate "sets" or "tables", then doing it in a DB will map more closely.

    I'm not an anti-DB bigot or anything like that.  I appreciate a complex query as much at the next programmer.  Usually, I try to push all the application logic into the database.  I just think when the data is tiny and the queries are simple, it's easier to use files.  This goes double for languages like PHP that have good support for arrays and associative arrays, because they can sometimes "act like" tables.  My usual policy is if I have to do a table join, I'll move it into a DB.

     

    by: jk2001Posted on 2006-12-12 at 02:49:24ID: 18121369

    Insomnia strikes again...

    I tested this script.  It's got some mangled URLs that aren't really "secret".  They'll just prevent some people from seeing the filenames and directories.  It does the image preload.  There can never be too many gallery scripts.

    <?php
    ###### user settings ################################

    $defaultDir = 'img'; // this must be set

    #####################################################

    $args = array_keys($_GET);
    $arg = $args[0];
    list($dir,$image) = unserialize(base64_decode($arg));

    // set a default dir
    if (!$dir) $dir = 'img';

    // validate directory
    if (preg_match("#(\.|/)#", $dir)) die('dots and slashes in dir disallowed');
    if (!is_dir($dir)) die('bad directory');

    include($dir."/captions.php");   // loads in captions

    // load all the images into an array
    $images = array_keys($captions);

    // if there's no image specified, use a default
    if (!$image) $image=$images[0];

    if (preg_match("#/#", $image)) die('slashes in image disallowed');

    if (!file_exists("$dir/$image")) die("image does not exist");

    // draw the navigation
    $nav = '';
    for($i=0; $i < count($images); $i++)
    {
        $img = $images[$i];
        $arg = base64_encode(serialize(array($dir,$img)));
        if ($img != $image)
           $nav .= "<a href=?$arg>".($i+1)."</a>";
        else
           $nav .= ($i+1).' ';
        if ($i < count($images) - 1) $nav .= ', ';
    }
    $nextImage = $images[$i];
    if (!$nextimage) $nextImage = $images[$i-1];
    ?>
    <html>
    <head>
    <style type="text/css">
    body {
          background-color: #eee;  
          font-size: 80%;
          font-family: "HelveticaNeue","Arial","Verdana";
    }
    .nav {
          text-align: center;
          padding: 5px;
          background-color: #ddd;
    }
    .content {
          text-align: center;
          padding: 30px;
          background-color: white;
          height: 100%;
    }
    .caption {
          padding: 10px;
    }

    </style>
    <body>
    <div class="nav">
          <?=$nav?>
    </div>
    <div class="content">
          <div class="image">
                <img src='<?=$dir?>/<?=$image?>'><br />
          </div>
          <div class="caption">
                <?=$captions[$image]?>
          </div>
    </div>
    <img src="<?=$dir?>/<?=$nextImage?>" width="1" height="1" />
    </body>
    </html>

     

    by: Eternal_StudentPosted on 2006-12-12 at 06:12:01ID: 18122434

    Excellent, is that as effective as pre-loading the images using javascript? I take it it loads the next image onto the page so it is downloaded into cache so when they click the next link it will appear pretty rapidly?

     

    by: jk2001Posted on 2006-12-12 at 09:15:40ID: 18124013

    Well, it's not quite as good, because it will try to load the next image simultaneously.  A really decent javascript preloader would wait until the first image loaded, then try to start loading the second.  You'd need to use setInterval() to run a function that would do the following:

     check that the main image is loaded
     if it is, then check if the next image is loaded into the second img tag's src
        if it is not, then set the second img tag's src to the next image.
     
    Also alter the script so that the image tags have IDs, and the second image tag should load a the main photo, not the next photo.

     

    by: Eternal_StudentPosted on 2006-12-14 at 02:12:53ID: 18137613

    If I did use javascript to pre-load the images [as I know what they will be called] would this work ok with your script?

     

    by: jk2001Posted on 2006-12-15 at 05:58:36ID: 18145975

    Sure.

    You can even pass the name of the next image like this:

    <script type="text/javascript">
    var nextImage = "<?=$dir.'/'.$nextImage?>";
    </script>

    And the rest of the script is hard-coded afterwards.

     

    by: Eternal_StudentPosted on 2006-12-17 at 03:59:28ID: 18154357

    Is it possible to pass 2 or 3 images into a javascript variable for pre-load?

     

    by: jk2001Posted on 2006-12-17 at 19:25:27ID: 18156486

    Yes.  Use the same technique to pass values to javascript, and write your code to preload them one by one.  You will need to add javascript code to check that an image has loaded, before loading the next image.

    20120131-EE-VQP-002

    3 Ways to Join

    30-Day Free Trial

    The Experts

    98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

    He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

    The Experts

    97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

    The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

    Testimonials

    "...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

    Testimonials

    "I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

    Testimonials

    "WOW! You guys have great, active, and knowledgeable people on here." moore50

    Business Clients

    Business Clients

    In the Press

    "If you’ve got a question... Experts Exchange can supply an answer.”

    In the Press

    "...an invaluable aid for both IT professionals and those who require tech support."

    In the Press

    "where IT professionals provide quick answers on just about any topic"

    Business Account Plans

    Loading Advertisement...