Show Newest/Oldest/Random using MySQL

Hi there.

Ive got the basic SQL statement on my page.

[php]
$getimages = mysql_query(“SELECT * FROM **** ORDER BY RAND() LIMIT 12”) or die(mysql_error());
//loops there name out
while ($image = mysql_fetch_array($getimages))
[/php]

Right, Ive got some buttons at the top of the page which say ‘Most Recent’ , ‘Oldest’ , ‘Random’.

Basically, i want it to do what each button says when it is clicked. I know to get the newest ID is replacing RAND() by DESC, and the oldest by ASC. But how do i do this by just clicking a button?

Totally baffled. Anyhelp is appreciated.

Thanks, Sam!

If your ‘Most Recent’ , ‘Oldest’ , ‘Random’ - are buttons, you can set a html form and just submit this form when one of buttons is clicked:

<form method="post">
<input type="submit" name="but_recent" value="Most Recent">
<input type="submit" name="but_oldest" value="Oldest">
<input type="submit" name="but_random" value="Random">
</form>

Then, in your php code, just check which of buttons was pressed, and generate your sql query conditionally:
[php]

<?php if($_POST["but_recent"]){ $sort = "ORDER BY id"; } elseif($_POST["but_oldest"]){ $sort = "ORDER BY id DESC"; } elseif($_POST["but_random"]){ $sort = "ORDER BY RAND()"; } $getimages = mysql_query("SELECT * FROM `****` ORDER BY $sort LIMIT 12") or die(mysql_error()); ?>

[/php]

If they are not buttons, but links - you can just include some key to the query string, like this:

<a href="page.php?sort=1">Most Recent</a>
Sponsor our Newsletter | Privacy Policy | Terms of Service