Forums

PHP

This topic is locked

Paging results from a randomly sorted select query

Posted 20 Mar 2007 20:31:10
1
has voted
20 Mar 2007 20:31:10 John Gaunt posted:
I am just starting with PHP/MySQL and using Dreamweaver MX 2004.
I am selecting a subset of records from a table, then ordering them using RAND() and then displaying 6 at a time on a page. This is so that I can present a good mix of records each time soemone visits the page rather than the same set. So far so good but there is one major problem, namely, when you move from page to page viewing the results the query is rerun for each page which means that you end up duplicating results. What I want to be able to do is run the query once and then page through the returned results without duplication. Also to be able to go back & forth between pages and see the same set of results.

Here's a simplified example: Suppose I have 12 records (call them A - L).
The query : SELECT * FROM Table WHERE Criteria = 1 ORDER BY RAND()
Which returns: D F K A L F J H G C B I
So my pages should show the following:
Page 1: D F K A L F
Page 2: J H G C B I
And I should be able to switch back and forth between these pages and always see exactly the same records each time.
However what I see at the moment is:
Page 1: D F K A L F
Page 2: F B C A E D (Note duplicates from Page 1 because query has been re-run)
Page 1: C B F A K L (Note duplicates again plus results not the same as previous visit to Page 1)

One thought I had was to run an initial query with the random order setting and then output the records to a temporary table which holds them in the random order. Then run a query on the temp table and page through this recordset. Sounds logical but not sure how to do this. Any thoughts?

Grateful for any ideas/help with this one. All my searches have been unsuccessful so maybe you are the guys to help.
Thanks in advance.

Replies

Replied 21 Mar 2007 16:19:23
21 Mar 2007 16:19:23 Alan C replied:
HI
not my specialist area really but I like the idea of putting the result set into a temp table, thinking about that how would the site cope two or more users browsing it at the same time . . .

My first thought was to save the results into an array which is saved in a php session, that way the result set would be kept for as long as that person was actively viewing. I do something like that when passing a list of results of a search then viewing just one of them in detail. In my case the site is about properties, so when a property manager views their properties I first run a query that finds all their properties and shows them, at the same time the unique identifiers for each property go into an array in the session.

Reply to this topic