SitePoint Sponsor

User Tag List

Results 1 to 21 of 21
  1. #1
    SitePoint Member
    Join Date
    Nov 2002
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Object Oriented PHP: Paging Result Sets

    Almost without troubles I implemented the class explained in 'Object Oriented PHP: Paging Result Sets', using it for searching in a MySQL-db.

    My question is: When the search is negative (when it not finds any matching rows), how to return a meaningful message to the user?

  2. #2
    SitePoint Evangelist
    Join Date
    Oct 2001
    Location
    Texas
    Posts
    598
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I too just finished implementing the OO paging results. I accomplished it as follows.

    PHP Code:
        if ( $rs->getNumPages() < )
            {
            print 
    "<p><b>No subscribed users at this time.</b></p>";
            }
        else
            {
            
    // Display the results
            
    while ( $row $rs->fetchArray())
     {
      
    your code here  etc etc etc 

  3. #3
    SitePoint Member
    Join Date
    Nov 2002
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thanks!

    I ended up with this:
    PHP Code:
    ECHO "<TABLE WIDTH=\"600\" BORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"3\">";
    IF ( 
    $rs->getNumPages() < ) {
        ECHO 
    "<TR><TD><b>Sorry - no results!</b></TD></TR>";
    }
    ELSE {
        
    // Display the results
        
    while ( $row $rs->fetchArray()) {
            
    $id $row["id"];
            
    $dato $row["dato"];
            
    $overskr $row["overskr"];

            
    us_dk($dato);
            
    type($overskr);

            ECHO 
    "<TR><TD><A HREF=\"single_konc.php?id=$id\" VALIGN=\"top\">$dato $overskr</A><BR></TD></TR>\n";
        }

    ECHO 
    "<TR><TD>"$rs->getPageNav("s_id=r&search_overskr=$search_overskr")."</TD></TR>";
    }
    ECHO 
    "</TABLE>"
    It seems to be working perfectly!
    Thanks!

  4. #4
    SitePoint Zealot dbworm's Avatar
    Join Date
    Apr 2003
    Location
    Lausanne
    Posts
    115
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I also tried that class and it works fine except for the navigation line. It's there, it advertises the right number of pages (with links) but it always stays on page 1, no matter what I click on. Here is my query:

    $conn = @mysql_connect('','','');
    mysql_select_db('mydb',$conn);
    $rs = new MySQLPagedResultSet("select * from visits",5,$conn);

    and here is my html implementation:

    <table border="1">
    <?php while ($row = $rs->fetchArray()): ?>
    <tr><td><?=$row['datestamp']?></td><td><?=$row['referer']?></td></tr>
    <?php endwhile; ?>
    </table>
    <p><?=$rs->getPageNav()?></p>

    I don't see where it could be wrong. Any idea?

    Thanks, Dan

  5. #5
    SitePoint Addict jough's Avatar
    Join Date
    Sep 2001
    Location
    You have moved into a dark place. It is pitch blac
    Posts
    248
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dbworm
    I also tried that class and it works fine except for the navigation line. It's there, it advertises the right number of pages (with links) but it always stays on page 1, no matter what I click on.
    I have the same problem. I see no one replied to this - did you ever get it working?

    Has anyone?

    -- Jough
    My Dynamic Site in Action:
    Poetry X Poetry Archive

  6. #6
    SitePoint Zealot dbworm's Avatar
    Join Date
    Apr 2003
    Location
    Lausanne
    Posts
    115
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by jough
    I have the same problem. I see no one replied to this - did you ever get it working?
    Yes, I did but frankly, I do not remember what was wrong. I only know that the mistake was on my side, not on the class's. Will let you know in case it comes back to me.

    Dan

  7. #7
    SitePoint Addict jough's Avatar
    Join Date
    Sep 2001
    Location
    You have moved into a dark place. It is pitch blac
    Posts
    248
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, I've tried the example exactly as it appears in the article - I even tried testing it with the same DB that Yank uses as his example.

    And as for the class, I just downloaded the file he provided.

    I get the correct listing of page numbers, but the "Next" link always points to page 1, the other pages always show the first 25 titles, and the links always link to the *last* 25 records. Very strange.

    Oh well, I guess I'll have to go back to the drawing board and write my own.

    -- Jough
    My Dynamic Site in Action:
    Poetry X Poetry Archive

  8. #8
    SitePoint Member cambiert's Avatar
    Join Date
    Jul 2003
    Location
    akron, OH
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Paged recordSet Example

    Has anyone gotten this to work yet??? I also get the page numbers but can only get to page 1. Please let me know if you have found anything helpful.

  9. #9
    SitePoint Addict jough's Avatar
    Join Date
    Sep 2001
    Location
    You have moved into a dark place. It is pitch blac
    Posts
    248
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Everyone who said that they got this working just by downloading the file in Yank's article is lying to you. There's no way it can work, because there are a few mistakes in the Yank article file.

    I re-wrote the script extensively, and mine uses a LIMIT clause to only return the results from the set that are used. This should save a little SQL overhead for large result sets.

    I added an extra parameter - webPage - which allows you to specify from the page invoking the class which page will be returned. I'm using mod_rewrite in my pages to parse the variables, so that users don't even see the GET vars, like resultPage, etc.

    I also added "countQuery" which is the query to return the count of the result set. I made this different than the $query var just to make things easier on myself when I was testing. This could probably be optimised.

    But a sample "countQuery" might be:

    $countQuery = "SELECT COUNT(ID) FROM TABLE WHERE ID='$ID'";

    By making it a parameter, you can specify the counted field, rather than having to COUNT(*), although in this case counting every matching record probably wouldn't hurt too much. I may integrate the record count into a class method in a later revision.

    Here's my code. You'd probably have to modify it to your own uses, but I commented it a little so that you should be able to figure out what's going on.

    Let me know if you have problems.

    -- Jough
    PHP Code:
    <?php
    #############################################################
    # Poetry X
    # Paged Results Class
    #
    # Based (loosely) on a SitePoint Tutorial by Kevin Yank:
    # [url=http://www.sitepoint.com/print/662]http://www.sitepoint.com/print/662[/url]
    #
    #############################################################
    class PagedResultSet
    {
    // Declare class variables
    var $results;
    var 
    $webPage;
    var 
    $pageSize;
    var 
    $page;
    var 
    $sqlCount;
    var 
    $recordStart;
    function 
    PagedResultSet($webPage,$query,$countQuery,$pageSize,$db)
    {
    //------------------------------------------------------------------
    // Class constructor
    //------------------------------------------------------------------
    // The current page is passed through a GET variable
    $this->page $_GET['resultPage'];
    // Return the total record count of the query
    $this->sqlCount mysql_result(mysql_query($countQuery,$db),0);
    // Set the current page URL
    $this->webPage $webPage;
    // Set the pageSize based on the constructor parameter
    $this->pageSize $pageSize;
    // Ensure that the page isn't zero or negative
    // If it is, set it to page 1
    if ($this->page <= 0)
    {
    $this->page 1;
    }
    // Set SQL Limit based on page number
    if ($this->page 1)
    {
    $recordStart $this->pageSize * ($this->page-1);
    }
    else
    {
    $recordStart 0;
    }
    // Append LIMIT clause to query string
    $query .= " LIMIT ";
    $query .= $recordStart;
    $query .= ",";
    $query .= $this->pageSize;
    // Set results sql resource id
    $this->results mysql_query($query,$db);
    // end PagedResultSet

    function getNumPages()
    {
    //------------------------------------------------------------------
    // Get the total number of pages
    //------------------------------------------------------------------
    // If the mysql query hasn't been made, get out
    if (!$this->results)
    {
    return 
    FALSE;
    }
    // Divide the total record count by the pageSize to determine
    // the total number of pages
    return ceil($this->sqlCount $this->pageSize);
    // end getNumPages

    function getPageNum()
    {
    //------------------------------------------------------------------
    // Returns the current page number
    //------------------------------------------------------------------
    return $this->page;
    }

    function 
    isLastPage()
    {
    //------------------------------------------------------------------
    // Determine if the page is the last page of the set
    //------------------------------------------------------------------
    return ($this->page >= $this->getNumPages());
    }

    function 
    isFirstPage()
    {
    //------------------------------------------------------------------
    // Determine if the page is the first page of the set
    //------------------------------------------------------------------
    return ($this->page <= 1);
    }

    function 
    fetchArray()
    {
    //------------------------------------------------------------------
    // Fetch the array from sql
    //------------------------------------------------------------------
    if (!$this->results)
    {
    return 
    FALSE;
    }
    // Return the results array
    return mysql_fetch_array($this->results);
    // end fetchArray

    function getPageNav()
    {
    //------------------------------------------------------------------
    // Creates the paginated navigation itself
    //------------------------------------------------------------------
    $nav .= "<div id=\"pageNav\">";
    // If the current page is not the first page,
    // display the "Prev" link
    if (!$this->isFirstPage())
    {
    $nav .= "<a class=\"pageNavDir\" href=""\"$this->webPage/".
    (
    $this->getPageNum()-1).'/">&laquo; Prev</a> ';
    }
    // Build the list of pages
    if ($this->getNumPages() > 1)
    {
    for (
    $i=1$i<=$this->getNumPages(); $i++)
    {
    if (
    $i==$this->page)
    {
    $nav .= "$i ";
    }
    else
    {
    $nav .= "<a href=""\"$this->webPage/{$i}"."/\">{$i}</a> ";
    }
    // END for ($i=1; $i<=$this->getNumPages(); $i++)
    // END if ($this->getNumPages() > 1)
    // If this isn't the last page, then add the "Next" link
    if (!$this->isLastPage() && $this->getNumPages() > 1)
    {
    $nav .= "<a class=\"pageNavDir\" href=""\"$this->webPage/".
    (
    $this->getPageNum()+1).'/">Next &raquo;</a>';
    }
    $nav .= "</div>";
    return 
    $nav;
    // end getPageNav
    // end PagedResultSet class
    ?>
    My Dynamic Site in Action:
    Poetry X Poetry Archive

  10. #10
    Anonymous
    SitePoint Community Guest
    great article!

  11. #11
    Anonymous
    SitePoint Community Guest
    This thing works great. Not a single mistake in the class for me. What a convenience!

  12. #12
    Knowledge is key 2 progression Tryst's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,181
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've just run the class and am getting the navigation probelm which everyone else has seemed to have encountered. My nav links dont work, I am stuck on the 1st listing of results.

    Does anyone know what the problem is??

    Tryst

  13. #13
    You talkin to me? Anarchos's Avatar
    Join Date
    Oct 2000
    Location
    Austin, TX
    Posts
    1,438
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You need to change
    PHP Code:
    global $resultpage
    to

    PHP Code:
    $resultpage $_GET['resultpage']; 
    ck :: bringing chris to the masses.

  14. #14
    Knowledge is key 2 progression Tryst's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,181
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ahh, cheers

    So the people who were getting it to work first time were the people who had register_globals turn on in their php.ini file...

    Tryst

  15. #15
    SitePoint Addict jough's Avatar
    Join Date
    Sep 2001
    Location
    You have moved into a dark place. It is pitch blac
    Posts
    248
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, there were other typos and mis-named variables in the download that would prevent it from working for anyone. Those who said it worked straight off (all anonymous, I should add) were lying.

    However, they could have fixed the .zip file recently. I'll have to take a look.
    My Dynamic Site in Action:
    Poetry X Poetry Archive

  16. #16
    Anonymous
    SitePoint Community Guest
    It worked immediately for me. I did have register_globals on however.

  17. #17
    Coding for Jesus LavernGingerich's Avatar
    Join Date
    Jul 2003
    Location
    Tennessee
    Posts
    607
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey, I am having trouble paging through my MySQL results. Can anyone please help me figure it out? http://www.sitepointforums.com/showt...ghlight=paging

    Any help would be greatly appreciated!
    Lavern

  18. #18
    SitePoint Enthusiast
    Join Date
    Jun 2001
    Location
    Iasi, Romania
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Kevin Yank paging script improved but a small bug

    Hi!
    I tried to fix some bugs in Kev's script for paging result set and I was ended with the code bellow:
    -my fixes are about isset $_GET['resultpage'] (it happened an error when displaying first page) and added support for URLs like index.php?page=search&searchresult=3
    -another fixes that doesn't belong to me is about counting all results and display a friendly message when no records are returned.
    See bellow how I call the class.
    My cry for help is about_:

    Undefined variable: nav in c:\easyphp\www\sq\classes\pagedresults.php on line 90
    where line 90 is
    PHP Code:
    $nav .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".$_SESSION['pageName']."&resultpage=". ($this->getPageNum()-1).$queryvars.'">Prev</a> '
    It is interesting that the navigation links works perfectly but this error constantly appears each place nav is assigned a value.

    PHP Code:
    <?php
    class MySQLPagedResultSet
    {
     
    var 
    $results;
    var 
    $pageSize;
    var 
    $page;
    var 
    $row;
    var 
    $resultpage;
     
     
    function 
    MySQLPagedResultSet($query,$pageSize,$cnx)
    {
     
    if (!isset (
    $_GET['resultpage']))
    {
    $resultpage=1;
    }
    else {
        
    $resultpage $_GET['resultpage'];
        }
     
        
    $this->results = @mysql_query($query,$cnx);
        
    $this->pageSize $pageSize;
        if ((int)
    $resultpage <= 0$resultpage 1;
        if (
    $resultpage $this->getNumPages())
         
    $resultpage $this->getNumPages();
        
    $this->setPageNum($resultpage);
    }
     
    function 
    getNumRecords() 

        if (!
    $this->results) return 0
     
        return 
    mysql_num_rows($this->results); 

     
     
     
    function 
    getNumPages()
    {
        if (!
    $this->results) return FALSE;
     
        return 
    ceil(mysql_num_rows($this->results) /
                    (float)
    $this->pageSize);
    }
     
    function 
    setPageNum($pageNum)
    {
        if (
    $pageNum $this->getNumPages() or
            
    $pageNum <= 0) return FALSE;
     
        
    $this->page $pageNum;
        
    $this->row 0;
        
    mysql_data_seek($this->results,($pageNum-1) * $this->pageSize);
    }
     
    function 
    getPageNum()
    {
        return 
    $this->page;
    }
     
    function 
    isLastPage()
    {
        return (
    $this->page >= $this->getNumPages());
    }
     
    function 
    isFirstPage()
    {
        return (
    $this->page <= 1);
    }
     
    function 
    fetchArray()
    {
        if (!
    $this->results) return FALSE;
        if (
    $this->row >= $this->pageSize) return FALSE;
        
    $this->row++;
        return 
    mysql_fetch_array($this->results);
    }
     
     
    function 
    getPageNav($queryvars '')
     
    {
    if (!
    $this->isFirstPage())
        {
     
         
    $nav .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".$_SESSION['pageName']."&resultpage=". ($this->getPageNum()-1).$queryvars.'">Prev</a> ';
     
    }
     
     
    if (
    $this->getNumPages() > 1)
         for (
    $i=1$i<=$this->getNumPages(); $i++)
         {
            if (
    $i==$this->page)
             
    $nav .= "$i";
            else
             
    $nav .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".$_SESSION['pageName']."&resultpage={$i}".$queryvars."\">{$i}</a> ";
         }
     
     
    if (!
    $this->isLastPage())
        {
         
    $nav .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".$_SESSION['pageName']."&resultpage=".
                 (
    $this->getPageNum()+1).$queryvars.'">Urmatorul</a> ';
        }
     
     
    return 
    $nav;
    }
    }
     
    ?>
    I call this class like this:

    PHP Code:
    <?php 
    //announces.php
    $pageName='announces';
    $_SESSION['pageName'] = $pageName
    include(
    './classes/pagedresults.php');
    $cnx = @mysql_connect('localhost','database','password'); 
    mysql_select_db('database',$cnx); 
    $rs = new MySQLPagedResultSet("select * from announces",2,$cnx); 
    ?> 
     
    <table border="1"> 
    <?php
    if ( $rs->getNumPages() < ) { 
    echo 
    "<TR><TD><b>Sorry - no results!</b></TD></TR>"

    else { 
    while (
    $row $rs->fetchArray()): ?> 
    <tr><td><?=$row['title']?></td><td><?=$row['announce']?></td></tr> 
    <?php endwhile; 
    }
    ?> 
    </table> 
    <p><?=$rs->getPageNav()?></p> 
    </body> 
    </html>
    Session is started when site index.php is first accessed so there is no problem here.

  19. #19
    SitePoint Enthusiast
    Join Date
    Jun 2001
    Location
    Iasi, Romania
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    solved the issue

    looking carefully to the code posted here before I fixed the problem: variable nav was not initialized. So I put
    PHP Code:
    function getPageNav($queryvars '')
        {
    $nav "<div id=\"pageNav\">";
     
    if (!
    $this->isFirstPage())
        {
     
    $nav .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".$_SESSION['pageName']."&resultpage=". ($this->getPageNum()-1).$queryvars.'">Precedentul</a>';
     

    and to the end of the script

    PHP Code:
    $nav .= "</div>";
    return 
    $nav

  20. #20
    SitePoint Zealot colinr's Avatar
    Join Date
    Aug 2003
    Location
    san francisco, ca
    Posts
    198
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can you overload memeber functions in PHP, Can you overload functions in general in PHP? I come from a C++(ish) background and really enjoied this added functionality (no pun intended)
    e.g.
    Could I add the following to you Rectangle class?
    PHP Code:
     function Rectangle(){
       
    $this->width 0;
       
    $this->height 0;
     } 
    Web Slave

  21. #21
    SitePoint Member bhutz's Avatar
    Join Date
    May 2004
    Location
    Bedford
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK, I have managed to get this working but a few changes were needed from the orginial version (Thanks Zico).

    I am having a problem with performance on the page that is display the results that actually calls the paging class...my browser attempts to load then pauses and it looks like it refreshes the page and tries again, eventually it display what I want but sometimes this takes a while...an ides why?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •