Add Pagination in PHP code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manas1
    New Member
    • Sep 2010
    • 4

    #1

    Add Pagination in PHP code

    I am working on php and mysql. Want to do pagination.
    Here is my flow:

    In the Login page user upload the document by giving there first_name, last_name, etc. In the login page also I have added search functionality. As per the query in the search field i am displaying the record.

    Right now I am able to displaying the record as per the search query but i want to add paging in the code. here is the code:


    My Home.html page code:

    Code:
    <!DOCTYPE html> 
    <head> 
        <title>Upload & Download Document</title> 
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    
    
    	<script type="text/javascript">
    
    
    function validate_required(field,alerttxt)
    {
    with (field)
      {
      if (value==null||value=="")
        {
        alert(alerttxt);return false;
        }
      else
        {
        return true;
        }
      }
    }
    
    
    function validate_form(thisform)
    {
    with (thisform)
      {
      if (validate_required(auther_first_name,"Auther First Name must be filled out!")==false)
      {auther_first_name.focus();return false;}
    
       if (validate_required(auther_last_name,"Auther Last Name must be filled out!")==false)
      {auther_last_name.focus();return false;}
    
     
    
     if(thisform['auther_first_name'].value == thisform['auther_last_name'].value) {
        alert('auther_first_name should not equals to auther_last_name');
        return false;
      }
    
    if (validate_required(topic_title,"Topic Title must be filled out!")==false)
      {topic_title.focus();return false;}
    
    
    if (validate_required(uploaded_file,"Please Browse the file you want to upload!")==false)
      {uploaded_file.focus();return false;}
    
      }
    
    
    
    }
    
    
    
    
    
    function validate_required1(field,alerttxt)
    {
    with (field)
      {
      if (value==null||value=="")
        {
        alert(alerttxt);return false;
        }
      else
        {
        return true;
        }
      }
    }
    
    
    
    function validate_form1(thisform)
    {
    with (thisform)
      {
    if (validate_required1(searchterm,"What you want to Search!")==false)
      {searchterm.focus();return false;}
    
      }
    
    
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    </script>
    
    
    
    
    
    
    </head> 
    <body bgcolor="#ffffcc">
    <br>
    
    
    <table ALIGN="CENTER">
    <tr>
    <td>
    <a href="Home.html">
    <img src="metasession_document_repository.png"/></a>
    </td>
    </tr>
    </table>
    
    <br>
    <hr size=10px color=darkblue>
    
    <font size="+3" color="green" ></font>
        <form action="add_file.php" onsubmit="return validate_form(this)" method="post" enctype="multipart/form-data">
    	
    	
    	<table ALIGN="CENTER">
    	<tr><td>
    	Fill your details Before uploading document !
    	</td></tr>
    	</table>
    	<table style="background-color: #ECE5B6;" width="30%" height="40%" ALIGN="CENTER">
    	<br />
    	
    	<tr>
    	      <th width="50%">Auther First Name:</th>
    		  <td width="50%"><INPUT type="text" name="auther_first_name"></td>
    	  </tr>
    	
    	
        <tr>
    	     <th width="50%">Auther Last Name:</th>
    		 <td width="50%"><input type="text" name="auther_last_name"></td>
    	  </tr>
    
    	
    
    	<tr>
    	     <th width="50%">Topic Title:</th>
    		 <td width="50%"><input type="text" name="topic_title"></td>
    	  </tr>
    
    
       <tr>
    	     <th width="100%" height="100%">Description:</th>
    		 <td width="100%" height="100%"><input type="text" name="description" maxlength="200"></td>
    	  </tr>
    
    
    
    	 
    	
       <tr>
    	     <th width="50%">Upload File:</th>
    		 <td width="50%"><input type="file" name="uploaded_file"></td>
    	  </tr>
    
    
    	
       <tr>
    	      <th></th>
    		  <td width="50%"><INPUT TYPE="submit" VALUE="Upload file"></td>
    	  </tr>
    
    
          </table>
    
        </form>
    </br>
    	<form>
    	<table style="background-color: #ECE5B6;" width="34%" ALIGN="CENTER">
    
        <tr>
           <td>
    		<a href="displayRecord.php">Click To See The List of Document Uploaded in Database Till Now</a>
    		</td>
    	</tr>
    	</table>
    	</form>
    
    </br>
    
    
    
    
    
    </br>
    </br>
    </br>
    </br>
    </br>
    <form action="searchdb.php" onsubmit="return validate_form1(this)" method="post">
    
    
    <table width="50%" ALIGN="CENTER">
    
    
    Search by <select size="1" name="selectfromlist" >
    <option value="auther_first_name">Auther Name</option>
    <option value="topic_title">Topic Title</option>
    <option value="data">Document</option>
    </select> 
    </br>
    </br>
    
    <input type="text" size="100" name="searchterm"/>
    </br>
    </br>
    <tr>
    
    <input type="submit" size = "10" value="Go">
    </td>
    
    
    
    
    
    
    
    </table>
    </form>
    
     
    </body> 
    </html>
    my searchdb.php code is:

    Code:
    <html>
    
    <body bgcolor="#ffffcc">
    
    <br>
    <table ALIGN="CENTER">
    <tr>
    <td>
    <a href="Home.html">
    <img src="metasession_document_repository.png"/></a>
    </td>
    </tr>
    </table>
    <br>
    
    
    <?php
    $space="                      ";
    /*set varibles from form */ 
    $searchterm = $_POST['searchterm'];
    $selectfromlist = $_POST['selectfromlist'];
    trim ($searchterm);
    trim ($selectfromlist);
    
    if (!$searchterm){ 
            
    } 
    /*add slashes to search term*/ 
    if (!get_magic_quotes_gpc()) 
    { 
    $searchterm = addslashes($searchterm);
    } 
    
    
    
    /* connects to database */
    @ $dbconn = new mysqli('localhost', 'aaa', 'aaa', 'upload_file');
    if (mysqli_connect_errno())  
    { 
     echo 'Error: Could not connect to database.  Please try again later.'; 
     exit; 
    } 
    /*query the database*/
    //$query = "SELECT fname, lname, info FROM customers WHERE fname LIKE '%$searchterm%'";
    
    $query = "select * from file where $selectfromlist like '%".$searchterm."%'";
    
    $result = $dbconn->query($query);
    
    
    
    
    
    /*number of rows found*/ 
    $num_results = $result->num_rows; 
    
    
    ?>
    
    
    
    </br>
    <table border="1" width="100%" style="background-color: #ECE5B6;" align="center" BORDERCOLOR=indigo>
    <tr bordercolor=red>
    		    <th>Sr. no</th>
    			<th>Auther First Name</th>
    			<th>Auther Last Name</th>
    			<th>Topic Title</th>
    			<th>Created Date</th>
    			<th>Download Here</th>
    
    		</tr>
    <?php
    
    
    /*loops through results*/ 
    for ($i=0; $i <$num_results; $i++) 
    { 
     $num_found = $i + 1;
     $row = $result->fetch_assoc();
     //###############################################################################################################################################
    
    
    echo "
    
    
    <tr>
    <td width=100px>$num_found.</td>
    </hr>
    <td width=300px>".($row['auther_first_name'])."</td>
    <td width=400px>".($row['auther_last_name'])."</td>
    <td width=400px>".($row['topic_title'])."</td>
    <td width=500px>".($row['created'])."</td>
    <td width=600px><a href='get_file.php?id={$row['id']}'>Download</a></td>
    </tr>
    
    ";
    
    
    
    }
    
    	    
    
    ?>
    </table>
     <?php
     echo '<p>Result Found : '.$num_results.'</p>';
    /*free database*/ 
    $result->free();
    $dbconn->close();
    ?>
    
    </body>
    </html>
    Last edited by Atli; Sep 21 '10, 01:09 AM. Reason: Please wrap your code examples in [code] ... [/code] tags.
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    First of all, Welcome to Bytes and I wish you had read the Forum Etiquette and used CODE TAGs.

    MySQL can help you do pagination using two mysql functions:

    COUNT() and LIMIT

    To do pagination you need to know 3 things:

    1. The total number of records
    2. The number of records you/user want per page.
    3. The current page number.

    There are many examples on Google if you want actual code. But here's the basic flow:

    1. COUNT() the number of records (you'll have two select statements, this count() is the first one)
    2. Build your LIMIT
    3. Run your second select statement to get the data with the LIMIT string tacked on to the end of it.

    Here's an example:
    Let's say our count returned 532 records and we want to display the first page at 30 records per page.

    LIMIT 0,30

    Second page:

    LIMIT 30,30

    Third:

    LIMIT 60,30 and so on...
    LIMIT 90,30
    LIMIT 120,30

    As you may have noticed, the first parameter of limit is a multiple of our page number, here's the formula:

    first param = (page_number - 1) * number_per_page ;
    secnd param = number_per_page ;

    I'm sure you're smart enough to turn this into php code:

    Code:
    $count = 532;
    $numPerPage = 20; 
    $currPage = 4; 
    
    $limitStr = 'LIMIT ' .($$currPage- 1) * $numPerPage .',' .$numPerPage;
    
    
    $query = "select * from file where $selectfromlist like '%".$searchterm."%' " . $limitStr;
    So how do you change pages? When you provide links to your next and previous, just subtract or add one to the $currPage variable. Send it to your page via GET or POST. (preferably $_GET).

    How do you prevent the user from going past the last page?

    532/30 = 17.333, so you have 18 pages total. Store this and make sure to disable the Next/Prev button if the $currPage is equal to 1 or 18, respectively.


    Get it? Got it?

    Good.

    Let me know if any questions,




    Dan

    Comment

    • manas1
      New Member
      • Sep 2010
      • 4

      #3
      I have created one separate php page called Search.php and in the Search.php I have added pagination code.
      Here is the code: Search.php

      Code:
      <?php
      //Connect to DB
      mysql_connect("localhost","root","mysql") or die("Unable to connect to SQL server"); 
      mysql_select_db("upload_file") or die("Unable to SELECT DB"); 
      
      $Limit = 7; //Number of results per page 
      $Selectfromlist=$_POST["selectfromlist"]; // Get the search tearm
      echo("Selectfromlist-----$Selectfromlist</br>");
      $SearchString=$_POST["searchterm"]; // Get the search tearm 
      echo("SearchString-----$SearchString</br>");
      If($SearchString == "") 
      //$SearchString=$_GET["searchterm"]; // Get the search tearm 
      If($SearchString == "") {
      echo"Nothing to Search For";
      exit();
      }
      $page = intval(@$_GET["page"]);     
      
      //$page=$_GET["page"]; //Get the page number to show
      If($page == "")
      $page=1; //If no page number is set, the default page is 1 
      
      //Get the number of results 
      $SearchResult=mysql_query("SELECT * FROM file WHERE '%$Selectfromlist%' LIKE '%$SearchString%'") or die(mysql_error()); 
      $NumberOfResults=mysql_num_rows($SearchResult); 
      
      //Get the number of pages 
      $NumberOfPages=ceil($NumberOfResults/$Limit);
      
      $SearchResult=mysql_query("SELECT * FROM file WHERE '%$Selectfromlist%' LIKE '%$SearchString%' ORDER BY '%$Selectfromlist%' LIMIT " . ($page-1)*$Limit . ",$Limit") or die(mysql_error());
      echo"<hr>";
      While($row = mysql_fetch_object($SearchResult)) {
      
      echo "auther_first_name---> $row->auther_first_name . <BR>";
      echo "auther_last_name--->  $row->auther_last_name . <BR>";
      echo "topic_title---> $row->topic_title . <BR>";
      echo"<hr>";
      } 
      
      $Nav=""; 
      If($page > 1) { 
      $Nav .= "<A HREF=\"Search.php?page=" . ($page-1) . "&SearchString=" .urlencode($SearchString) . "\"> << Prev</A></br>";
      
      } 
      for($i = 1 ; $i <= $NumberOfPages ; $i++) {
      If($i == $page) { 
      $Nav .= "<B>$i</B>";
      }else{ 
      $Nav .= "<A HREF=\"Search.php?page=" . $i . "&SearchString=" .urlencode($SearchString) . "\">$i</A></br>";
      
      } 
      } 
      If($page < $NumberOfPages) { 
      $Nav .= "<A HREF=\"Search.php?page=" . ($page+1) . "&SearchString=" .urlencode($SearchString) . "\">Next >></A></br>";
      
      } 
      
      Echo "<BR><BR>" . $Nav;
      ?>
      Right now I am using Home.html and Search.php file code. Not searchdb.php file.
      I am getting the result in the first page.If i click 2nd page hiperlink page I am getting error like:

      Code:
      Notice: Undefined index: selectfromlist in C:\wamp\www\upload\Search.php on line 7
      Selectfromlist-----
      
      Notice: Undefined index: searchterm in C:\wamp\www\upload\Search.php on line 9
      SearchString-----
      Nothing to Search For
      I am not sure why and where exactly showing error.
      I have attached the error screenshots.
      Please help me on this.
      Thanks
      Attached Files
      Last edited by Markus; Sep 21 '10, 09:35 AM. Reason: Fixed [CODE] tags

      Comment

      • dlite922
        Recognized Expert Top Contributor
        • Dec 2007
        • 1586

        #4
        It's always good to know how to troubleshoot your code.

        Since many things depending on your own app can produce relatively generic errors like this, it's best to trace your code and your variables using echo's, print_r() and var_dump().

        use die() to end execution at that point.

        So...

        Trace your code and verify the content of each important variable like this

        Code:
        die(var_dump($myvar));
        In your case the clue says line 7:

        Code:
        $Selectfromlist=$_POST["selectfromlist"];
        Undefined index means the super global array $_POST doesn't have an index called "selectfromlist ".

        It should? well let's find out

        Right before that line put the following:

        Code:
        die(print_r($_POST));
        That will show everything that's in POST. is selectfromlist there? in the exact SPELLING??

        You most likely misspelled it on your html page.


        Dan

        Comment

        • manas1
          New Member
          • Sep 2010
          • 4

          #5
          I have added die(print_r($_P OST)); before $searchterm=$_P OST["searchterm "];
          I am getting the result:

          Array ( [selectfromlist] => auther_first_na me [searchterm] => a ) 1 and in the browser I am getting this url: http://localhost/upload/Search.php?page=2&searchterm=a

          Also i have checked the Home.html everything looks fine. selectfromlist and searchterm vriable is defined in the Home.html file. For your reference I am posting the code for Home.html and Search.php code again.

          Please help me on this. I am not able to identify where the error coming exactly.

          Home.html
          Code:
          <!DOCTYPE html> 
          <head> 
              <title>Upload & Download Document</title> 
              <meta http-equiv="content-type" content="text/html; charset=UTF-8">
              <script type="text/javascript">
          function validate_required(field,alerttxt)
          {
          with (field)
            {
            if (value==null||value=="")
              {
              alert(alerttxt);return false;
              }
            else
              {
              return true;
              }
            }
          }
          function validate_form(thisform)
          {
          with (thisform)
            {
            if (validate_required(auther_first_name,"Auther First Name must be filled out!")==false)
            {auther_first_name.focus();return false;}
          
             if (validate_required(auther_last_name,"Auther Last Name must be filled out!")==false)
            {auther_last_name.focus();return false;}
          
           if(thisform['auther_first_name'].value == thisform['auther_last_name'].value) {
              alert('auther_first_name should not equals to auther_last_name');
              return false;
            }
          
          if (validate_required(topic_title,"Topic Title must be filled out!")==false)
            {topic_title.focus();return false;}
          
          
          if (validate_required(uploaded_file,"Please Browse the file you want to upload!")==false)
            {uploaded_file.focus();return false;}
          
            }
          
          }
          function validate_required1(field,alerttxt)
          {
          with (field)
            {
            if (value==null||value=="")
              {
              alert(alerttxt);return false;
              }
            else
              {
              return true;
              }
            }
          }
          function validate_form1(thisform)
          {
          with (thisform)
            {
          if (validate_required1(searchterm,"What you want to Search!")==false)
            {searchterm.focus();return false;}
          
            }
          
          }
          </script>
          </head> 
          <body bgcolor="#ffffcc">
          <br>
          <table ALIGN="CENTER">
          <tr>
          <td>
          <a href="Home.html">
          <img src="metasession_document_repository.png"/></a>
          </td>
          </tr>
          </table>
          <br>
          <hr size=10px color=darkblue>
          
          <font size="+3" color="green" ></font>
              <form action="add_file.php" onsubmit="return validate_form(this)" method="post" enctype="multipart/form-data">
          <table ALIGN="CENTER">
              <tr><td>
              Fill your details Before uploading document !
              </td></tr>
          </table>
          <table style="background-color: #ECE5B6;" width="30%" height="40%" ALIGN="CENTER">
              <br />
              
              <tr>
                    <th width="50%">Auther First Name:</th>
                    <td width="50%"><INPUT type="text" name="auther_first_name"></td>
                </tr>
              
              
              <tr>
                   <th width="50%">Auther Last Name:</th>
                   <td width="50%"><input type="text" name="auther_last_name"></td>
              </tr>
          
              <tr>
                   <th width="50%">Topic Title:</th>
                   <td width="50%"><input type="text" name="topic_title"></td>
              </tr>
             <tr>
                  <th width="100%" height="100%">Description:</th>
                  <td width="100%" height="100%"><input type="text" name="description" maxlength="200"></td>
                </tr>
             <tr>
                   <th width="50%">Upload File:</th>
                   <td width="50%"><input type="file" name="uploaded_file"></td>
             </tr>
             <tr>
                   <th></th>
                   <td width="50%"><INPUT TYPE="submit" VALUE="Upload file"></td>
             </tr>
                </table>
          
          </form>
          </br>
              <form>
              <table style="background-color: #ECE5B6;" width="34%" ALIGN="CENTER">
          
              <tr>
                 <td>
                  <a href="displayRecord.php">Click To See The List of Document Uploaded in Database Till Now</a>
                  </td>
              </tr>
              </table>
              </form>
          </br>
          </br>
          </br>
          </br>
          </br>
          </br>
          <form action="Search.php" onsubmit="return validate_form1(this)" method="post">
          <table width="50%" ALIGN="CENTER">
          Search by <select size="1" name="selectfromlist">
          <option value="auther_first_name">Auther Name</option>
          <option value="topic_title">Topic Title</option>
          <option value="data">Document</option>
          </select>
          </br>
          </br>
          <input type="text" size="100" name="searchterm"/>
          </br>
          </br>
          <tr>
          <input type="submit" size = "10" value="Go">
          </td>
          </table>
          </form>
          </body> 
          </html>

          Search.php

          Code:
          <?php
          //Connect to DB
          mysql_connect("localhost","root","mysql") or die("Unable to connect to SQL server");
          
          mysql_select_db("upload_file") or die("Unable to SELECT DB"); 
           
          $Limit = 7; //Number of results per page
          
          die(print_r($_POST));
          
          $selectfromlist=$_POST["selectfromlist"]; // Get the value from the list
          
          echo("selectfromlist-----$selectfromlist</br>");
          
          $searchterm=$_POST["searchterm"]; // Get the search field
          
          echo("searchterm-----$searchterm</br>");
          
          If($searchterm == "") {
          
          echo"Nothing to Search For";
          
          exit();
          
          }
          
          $page = intval(@$_GET["page"]);     
           
          //$page=$_GET["page"]; //Get the page number to show
          If($page == "")
          
          $page=1; //If no page number is set, the default page is 1 
           
          //Get the number of results 
          $SearchResult=mysql_query("SELECT * FROM file WHERE '%$selectfromlist%' LIKE '%$searchterm%'") or die(mysql_error());
          
          $NumberOfResults=mysql_num_rows($SearchResult); 
           
          //Get the number of pages 
          $NumberOfPages=ceil($NumberOfResults/$Limit);
           
          $SearchResult=mysql_query("SELECT * FROM file WHERE '%$selectfromlist%' LIKE '%$searchterm%' ORDER BY id LIMIT " . ($page-1)*$Limit . ",$Limit") or die(mysql_error());
          
          echo"<hr>";
          
          While($row = mysql_fetch_object($SearchResult)) {
           
          echo "auther_first_name---> $row->auther_first_name . <BR>";
          
          echo "auther_last_name--->  $row->auther_last_name . <BR>";
          
          echo "topic_title---> $row->topic_title . <BR>";
          
          echo"<hr>";
          } 
           
          $Nav="";
          
          If($page > 1) {
          
          $Nav .= "<A HREF=\"Search.php?page=" . ($page-1) . "&searchterm=" .urlencode($searchterm) . "\"> << Prev</A></br>";
           
          }
          
          for($i = 1 ; $i <= $NumberOfPages ; $i++) {
          
          If($i == $page) {
          
          $Nav .= "<B>$i</B>";
          
          }else{
          
          $Nav .= "<A HREF=\"Search.php?page=" . $i . "&searchterm=" .urlencode($searchterm) . "\">$i</A></br>";
           
          }
          
          }
          
          If($page < $NumberOfPages) {
          
          $Nav .= "<A HREF=\"Search.php?page=" . ($page+1) . "&searchterm=" .urlencode($searchterm) . "\">Next >></A></br>";
           
          } 
           
          Echo "<BR><BR>" . $Nav;
          
          ?>

          Comment

          • manas1
            New Member
            • Sep 2010
            • 4

            #6
            Hello Dan, I have facing the same problem. Not able to identify where the error exactly coming from. I have posted details in my last reply. Please help me on this.

            Comment

            Working...