| Forum Home | ||||
| Press F1 | ||||
| Thread ID: 116082 | 2011-02-16 03:14:00 | php mysql help need to extract 5 random records from 20 most recent | Morgenmuffel (187) | Press F1 |
| Post ID | Timestamp | Content | User | ||
| 1178731 | 2011-02-16 03:14:00 | Hi all My problem is this, I have a database with thousands of records, I need to extract a random 5 of the 20 most recent records. I can get the 20 most recent easily enough its getting 5 random ones from those, is the problem $sql = "SELECT pid, filepath, filename, title, caption FROM `cpg_pictures` WHERE approved = 'YES' AND pwidth > '450' AND pheight > '370' ORDER BY pid DESC LIMIT 0 , 20"; $row = $result = mysql_query($sql, $conn) or die(mysql_error()); //$row = array_rand($result,5); while ($row_result = mysql_fetch_array($row)) { echo '<br>'.$row_result["filename"].'-'.$row_result["pid"].'<br>'; } any help appreciated |
Morgenmuffel (187) | ||
| 1178732 | 2011-02-16 03:46:00 | SELECT * FROM ( SELECT pid, filepath, filename, title, caption FROM `cpg_pictures` WHERE approved = 'YES' AND pwidth > '450' AND pheight > '370' ORDER BY pid DESC LIMIT 0 , 20 ) `top_20` ORDER BY RAND() LIMIT 0, 5 |
Erayd (23) | ||
| 1178733 | 2011-02-16 04:15:00 | If the records are randomly added could you just take 5 in the same order each time? Probaly wouldn't make much difference to the code though | hueybot3000 (3646) | ||
| 1178734 | 2011-02-16 04:17:00 | If the records are randomly added could you just take 5 in the same order each time? Probaly wouldn't make much difference to the code thoughI think the whole point was that he wanted to take a random sample of 5 from the top 20 - *not* the same 5 every time. | Erayd (23) | ||
| 1178735 | 2011-02-16 04:42:00 | Cheers Erayd, you're a life saver I've spent the best part of a day on that, doing all sorts of convoluted things, never even thought to try it that way |
Morgenmuffel (187) | ||
| 1 | |||||