0

I'm creating a search feature with pagination.

I have a form and I get it's POST value. I then use this to search the database and return a set of results.

The results are broken up in to pages and a user can click page links in the view.

My question is, how can I persist the search over multiple pages?

Should the first page get the POST value and on subsequent pages should I put the search term into the url, eg.

www.example.com/search/various-keywords/p2

Then get the term and query the database again, splitting the results to whatever page it is, p2, p3, p4 etc.

Is there a cleaner way to do this?

Also, is it unsafe to include the users input in the url? Should I encode it in some way?

And if the user was to click back after going through a number of pages I would get the 'Confirm Form Resubmission' error. How can I prevent this?

panthro
  • 22,779
  • 66
  • 183
  • 324

3 Answers3

1

The best way to do this is making the search term a GET variable so you can always retrieve it and add it to any url you want.

As long as you escape the search query you should be fine with user security, this will also remove the re-submission of form error.

Lost F.
  • 410
  • 3
  • 15
  • Thanks, so I just need to change form method to get? – panthro Jun 27 '14 at 10:30
  • @panthro Yup, and then you need to parse that GET variable to your pagination urls of course! – Lost F. Jun 27 '14 at 10:31
  • @panthro You need to change your form method go GET and then you should have the variable in $_GET['NAME OF THE INPUT']. If that is not the case there is something else wrong. – Lost F. Jun 27 '14 at 10:39
  • Thanks, you've been most helpful. Juts one final thing, security: how should I 'escape the search query'? – panthro Jun 27 '14 at 10:41
  • It depends on how you're connecting to the database and how you fire your query. Could you post an example so I can review what the best method is? – Lost F. Jun 27 '14 at 10:43
  • It's just a mysql connection, no PDO. – panthro Jun 27 '14 at 10:58
  • Then http://www.php.net//manual/en/mysqli.real-escape-string.php should be needed. – Lost F. Jun 27 '14 at 11:12
1

Search should use a GET method, it's the RESTful way. Add the search term to the URL (make sure it is escaped):

http://www.example.com/search?q=example+search+term&page=1

If you have a <form>, it will take care of escaping:

<form action="search" method="GET">
    <input type="text" name="q" />
    <input type="submit" value="Search" />
</form>

For example if you enter test & test, it will become search?q=test+%26+test.

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
0

You can either pass the search phrases via the URI, like www.example.com/search?q=My+Search+Terms&page=1 or you can use Cookies or Sessions if you see it fit.

Mario Werner
  • 1,771
  • 14
  • 24