Question : How can I pull random posts from a database, no repeats, using php and ajax....

Hi,

I have looked everywhere but am unable to find a solution to this. I have a database of posts, I need to create a page that displays these posts one at a time randomly, with two buttons saying "Yes" and "No". When a user clicks on either button it triggers a backend function in php ( basically just votes the post up or down ), then loads another post which replaces the current one using ajax, no page refresh. Then you click Yes or No again, it loads another post etc... It also has to have no repeats, so once a post has been seen by someone and they have said yes or no, it won't show them it again unless the page is refreshed or the session closed.

This has to be in php and any ajax library.

I figured that maybe when the page is first loaded the php script would randomly populate an array with maybe 100 posts from the database, then using ajax you would pick one at a time from this array some how and display it on the page with the buttons. So basically you are voting up or down each post one at a time.

If anyone can help that would be great.
Thanks

Answer : How can I pull random posts from a database, no repeats, using php and ajax....

One other method:

In the PHP function called by Ajax use query something like WHERE post_id NOT IN ($shown) ORDER BY RAND() LIMIT 1
and for $shown can be added to the $_SESSION each time one post is displayed.
In this method even if the user refreshes the browser the shown can be retained. If you don't want to retain the shown list on refresh you can clear up the $_SESSION['shown'] variable in that page.

Some pseudo code:

// Start your session
session_start();

$shown='';
if (!empty($_SESSION['shown']) && is_array($_SESSION['shown']) ){
   $shown = implode(',',$_SESSION['shown']);
}
if (!empty($shown)){
  SELECT post, post_id FROM post_table WHERE yourconditions AND post_id NOT IN ($shown) ORDER BY RAND() LIMIT 1
}else{
  SELECT post, post_id FROM post_table WHERE yourconditions ORDER BY RAND() LIMIT 1
}
$_SESSION['shown'][]=$post_id;
Random Solutions  
 
programming4us programming4us