Jump to content

Pagination question for limiting search results


mike2

Recommended Posts

Hi Everyone,

 

I have a question about pagination. I have this code that I would like to incorporate into my php file.

 

This is said code that will be incorporated:

 

 

 
try {

    // Find out how many items are in the table
    $totalItems = $databaseHandle->query('
        select
            count(*)
        from
            tableName
    ')->fetchColumn();

    // Set how many items per page to display
    $limit = 10;

    // find how many pages are needed
    $totalPages = ceil($totalItems / $limit);

    // Find out which page we are on
    $currentPage = min($totalPages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
        'options' => array(
            'default'   => 1,
            'min_range' => 1,
        ),
    )));

    // Calculate the offset for the query
    $offset = ($page - 1)  * $limit;

    // Some information to display to the user
    $start = $offset + 1;
    $end = min(($offset + $limit), $total);

    // "back" link
    $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($currentPage - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>';

    // "forward" link
    $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $totalPages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>';

    // Display the paging information
    echo '<div id="paging"><p>', $prevlink, ' Page ', $currentPage, ' of ', $totalPages, ' pages, displaying ', $start, '-', $end, ' of ', $totalItems, ' results ', $nextlink, ' </p></div>';

    // Get the results. Paged query
    $stmt = $databaseHandle->prepare('
        select
            *
        from
            tableName
        order by
            name
        limit
            :limit
        offset
            :offset
    ');

    // Bind the query params
    $stmt->bindParam(':limit', $limit, PDO:: PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO:: PARAM_INT);
    $stmt->execute();

    // Results?
    if ($stmt->rowCount() > 0) {
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $iterator = new IteratorIterator($stmt);

        // Display the results
        foreach ($iterator as $row) {
            echo '<p>', $row['name'], '</p>';
        }

    } else {
        echo '<p>No results could be displayed.</p>';
    }

} catch (Exception $e) {
    echo '<p>', $e->getMessage(), '</p>';
}

 

and this is what is in my php file:

 

 

<html>
  <head></head>
  <body>
  <?php if (!isset($_POST['q'])) { ?>


<img src="/wvb-logo-slogen.png" border="0" />
    <h2>Search</h2>
    <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
      <input type="text" name="q" size="30" />
    </form>

  <?php } else { ?>

<img src="/wvb-logo-slogen.png" border="0" />
    <h2>Search Results</h2>

  <?php
    try {
      // create object
     // $swish = new Swish('/usr/local/apache/htdocs/swish/index.swish-e');
        $swish = new Swish('/var/www/html/pdf2/index.swish-e');


      // get and run query from command-line
      $queryStr = htmlentities($_POST['q']);
      $result = $swish->query($queryStr);
  ?>

   Found <?php echo $result->hits; ?> match(es) for '<?php echo $queryStr; ?>'.

  <?php
      // iterate over result set
      // print details for each match
      while($r = $result->nextResult()) {
   ?>

  <p>
    <?php echo $r->swishreccount; ?>
      <strong>
      <a href="<?php echo '/pdf2', ltrim($r->swishdocpath, '.') ;  ?>">
         <?php echo $r->swishdocpath; ?>
      </a>
   </strong> (score: <?php echo $r->swishrank; ?>) <br/>
<?php echo $r->swishdocpath; ?><br />
<?php

$file = '/var/www/html/active_colist.csv';
$fh = fopen($file, 'r');
$companies = array();
$row = fgetcsv($fh, 1024); // ignore header
while ($row = fgetcsv($fh, 1024)) {
    $companies[$row[0]] = array('company' => $row[1], 'country' => $row[3]); //changed line
   }
fclose($fh);


//Split a filename  by .
$filenames = explode(".", $r->swishdocpath);
//get 3 chars from $filenames to $country
$wvb_number = substr($filenames[1],1,12);
$country = substr($filenames[1],1,3);
echo 'Country: '.$companies[$wvb_number]['country']."<br />";
//echo 'Country Name: '.$country."<br />";
//$filenames[2] = explode(".", $r->swishdocpath);
$year = substr($filenames[2],0,4);
echo 'Year: '.$year."<br />";
//$filenames = explode(".", $r->swishdocpath);
//$wvb_number = substr($filenames[1],1,12);
echo 'WVB Number: '.$wvb_number."<br />";
echo 'Company Name: '.$companies[$wvb_number]['company'];
//echo 'Country: '.$companies[$wvb_number]['country'];

?>


  </p>

  <?php
      }
    } catch (Exception $e) {
      die('ERROR: ' . $e->getMessage());
    }
  }
  ?>

  </body>
</html>
 

 

My question is what would be the best way incorporate this into my php file so that I am able to display a limit number link by page so that not all of the results are listed on the same page? If that is even possible.

 

Link to comment
Share on other sites

swish has a ->seekResult() method - http://www.php.net/manual/en/swishresults.seekresult.php that would allow you to seek to the starting point in the swish result set. this would use the $offset value from the pagination code. you would then loop, up to the $limit times, calling the ->nextResult() method to get up to $limit rows from the result.

 

you could also just initially store all the swish results in an array, in a session variable, and use array_slice() to paginate the array. the $offset and $limit from the pagination code would be the offset and length parameters in the array_slice() statement.

Edited by mac_gyver
Link to comment
Share on other sites

swish has a ->seekResult() method - http://www.php.net/manual/en/swishresults.seekresult.php that would allow you to seek to the starting point in the swish result set. this would use the $offset value from the pagination code. you would then loop, up to the $limit times, calling the ->nextResult() method to get up to $limit rows from the result.

 

you could also just initially store all the swish results in an array, in a session variable, and use array_slice() to paginate the array. the $offset and $limit from the pagination code would be the offset and length parameters in the array_slice() statement.

Okay. I will try doing that but my question is would this negatively affect my Swish-e search results?

Link to comment
Share on other sites

swish has a ->seekResult() method - http://www.php.net/manual/en/swishresults.seekresult.php that would allow you to seek to the starting point in the swish result set. this would use the $offset value from the pagination code. you would then loop, up to the $limit times, calling the ->nextResult() method to get up to $limit rows from the result.

 

you could also just initially store all the swish results in an array, in a session variable, and use array_slice() to paginate the array. the $offset and $limit from the pagination code would be the offset and length parameters in the array_slice() statement.

How would I do that though? Would that code be at the very beginning before my search results or after?

Link to comment
Share on other sites

Okay. I will try doing that but my question is would this negatively affect my Swish-e search results?

 

 

define: would this negatively affect my Swish-e search results? all you are doing is changing how the results are displayed on the page. what negative effect are you worried about? btw - this page is getting and displaying data, your search form should use method='get' as this will allow you to easily propagate the search term with the pagination links.

 

How would I do that though? Would that code be at the very beginning before my search results or after?

 

 

modifying the code to include pagination will pretty much require a rethinking of your current code layout. what you have now is a html document that has php logic pasted into it to produce the overall document.

 

what you need is a separation of the 'business logic' (determines what to do on the page and gets the data the page needs) from the 'presentation logic' (deals only with the production of the html/css/javascript output.)

 

the reason for needing to rearrange the logic is the pagination code needs things like the $totalItems (this is your $result->hits value) and your swish code needs to use the $offset/$limit to accomplish the pagination. i also see that your .csv file code is inside your main data retrieval while(){} loop, running every time the loop runs. this code should run only once to produce the $companies array, i.e. it's part of the 'business logic'.

 

edit: i also see that you have duplicated the wvb-logo-slogen.png image tag. you should not duplicate code/markup and reorganizing the logic on the page will help you see duplication since it cleans up the whole layout of the code.

Edited by mac_gyver
Link to comment
Share on other sites

i would also add that i suggested two different methods, you would need to pick one.

 

you would use the first method if the underlying data is dynamic and could change during the visit to your site by any person, so that the changes would show up in the data. this method uses more resources since the swish query will be executed on every page load, not just when the search term gets changed.

 

the second method would use less server resources, but the data would be static for the duration of one search/the visit to your site since the data from one single swish query/search would be stored in a session variable.

Link to comment
Share on other sites

i would also add that i suggested two different methods, you would need to pick one.

 

you would use the first method if the underlying data is dynamic and could change during the visit to your site by any person, so that the changes would show up in the data. this method uses more resources since the swish query will be executed on every page load, not just when the search term gets changed.

 

the second method would use less server resources, but the data would be static for the duration of one search/the visit to your site since the data from one single swish query/search would be stored in a session variable.

The user would not be allowed to change the PDF files. However PDF files would be constantly uploaded to the site. I have 5000 PDF files indexed at the moment.

Link to comment
Share on other sites

define: would this negatively affect my Swish-e search results? all you are doing is changing how the results are displayed on the page. what negative effect are you worried about? btw - this page is getting and displaying data, your search form should use method='get' as this will allow you to easily propagate the search term with the pagination links.

 

 

modifying the code to include pagination will pretty much require a rethinking of your current code layout. what you have now is a html document that has php logic pasted into it to produce the overall document.

 

what you need is a separation of the 'business logic' (determines what to do on the page and gets the data the page needs) from the 'presentation logic' (deals only with the production of the html/css/javascript output.)

 

the reason for needing to rearrange the logic is the pagination code needs things like the $totalItems (this is your $result->hits value) and your swish code needs to use the $offset/$limit to accomplish the pagination. i also see that your .csv file code is inside your main data retrieval while(){} loop, running every time the loop runs. this code should run only once to produce the $companies array, i.e. it's part of the 'business logic'.

 

edit: i also see that you have duplicated the wvb-logo-slogen.png image tag. you should not duplicate code/markup and reorganizing the logic on the page will help you see duplication since it cleans up the whole layout of the code.

Here in lies my problem with changing the layout of the code:

 

I have never used php coding before to do a project like this. This project was assigned to me for work and I have mostly been getting help from people who do know php. I e-mailed this one particular individual to see if he would be willing to do it for me and if so would he charge me because to be quite honest with you I am not sure I am going to have this completed by the June 20th date. 

 

Would it be wrong of me to send you the complete details of what I am trying to accomplish as well as ask if either you or someone you know whom you could recommend would be willing to do it for me?

 

I am in way over my head here. I have never done anything like this before and I am getting desperate to get this project completed because I don't want to get in trouble for not having this completed on time.

Edited by mike2
Link to comment
Share on other sites

Would it be wrong of me to send you the complete details of what I am trying to accomplish as well as ask if either you or someone you know whom you could recommend would be willing to do it for me?

 

 

yes, it would be wrong. there's a forum rule -

 

16. Users are not allowed to contact members or staff members with the intention of receiving help with subjects covered in any boards.

 

 

basically, programming help forums are for programmers or those learning programming to get help (publicly, in the forum, so that problems and solutions would be of help to others) when they get stuck, after they have made an attempt at solving their programming problem. programming help forums are not script repositories, nor are we here to find or give you code that does what you want.

 

since you have no php/coding experience, the only progress being made is by others writing up code for you, in the location where it's needed. that's not what help means.

 

i recommend that you post in the Job Offerings forum section. you would want to list all the features at once since the overall design needs to take into account everything to avoid backtracking/rewriting that occurs when doing programming in a piecemeal fashion.

 

btw - there's three different ways of replying to a thread that doesn't involve hitting the quote button. quoting everything just makes for a long thread to read or scroll over to find the actual information being posted.

Link to comment
Share on other sites

Here in lies my problem with changing the layout of the code:

 

I have never used php coding before to do a project like this. This project was assigned to me for work and I have mostly been getting help from people who do know php. I e-mailed this one particular individual to see if he would be willing to do it for me and if so would he charge me because to be quite honest with you I am not sure I am going to have this completed by the June 20th date. 

 

Would it be wrong of me to send you the complete details of what I am trying to accomplish as well as ask if either you or someone you know whom you could recommend would be willing to do it for me?

 

I am in way over my head here. I have never done anything like this before and I am getting desperate to get this project completed because I don't want to get in trouble for not having this completed on time.

To answer your question honestly I am worried that my output is not going to come out correctly. I am concerned it is going to come out with lines skipped. Also are you sure that I need to rearrange this code? Can't I just incorporate this code somewhere?

Link to comment
Share on other sites

programming is not for the timid. you have to be willing to try things (on a development system) and in fact since programming gives you immediate feedback as soon as you run your code, it's easy to see if something you wrote or changed produced the intended result.

 

that you are asking if you cannot just incorporate the pagination code somewhere in your main code (you can, but you have to figure out which parts of it would be used at all, where each of the remaining functional parts of it would go, and what changes you would need to make to your main code to retrieve the correct rows based on which page of results has been requested) or are asking where in your code something that someone suggested should be put, says you are not at the point of understanding enough about what the code you have is doing to be able to write or change things in it (the posted pagination code itself contains several mismatched variables that would prevent it from working as is), so it's going to be a little hard for you to complete the current task unless you manage to acquire some skills to read and understand what the code is doing and to combine it in a way the produces the functionality that you need.

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.