note 105095 added to function.rand
| From: | ilya dot iz at i dot ua | Date: | Wed, 27 Jul 2011 15:09:02 +0000 |
| Subject: | note 105095 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-181934@lists.php.net to get a copy of this message | ||
I had to come up with a quick way to get a random row from a table, and came up with the following:
<?php
$query = "SELECT
id FROM [TABLE]";
$result = mysql_query($query, $link);
$num = mysql_num_rows($result);
if ($num > 0) {
// Array the ID's...
$id_array = array();
while ($row = mysql_fetch_assoc($result)) {
$id_array []=$row["id"];
}
$query = "SELECT * FROM [TABLE] WHERE id=".$id_array[rand(0,
(count($id_array)-1))];
$result = mysql_query($query, $link);
$row = mysql_fetch_assoc($result);
// ...
}
?>
LOL
SELECT * from [TABLE] ORDER BY rand() LIMIT 1
----
Server IP: 69.147.83.197
Probable Submitter: 93.127.109.20
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/105095
Del: integrated -- https://master.php.net/note/delete/105095/integrated
Del: useless -- https://master.php.net/note/delete/105095/useless
Del: bad code -- https://master.php.net/note/delete/105095/bad+code
Del: spam -- https://master.php.net/note/delete/105095/spam
Del: non-english -- https://master.php.net/note/delete/105095/non-english
Del: in docs -- https://master.php.net/note/delete/105095/in+docs
Del: other reasons-- https://master.php.net/note/delete/105095
Reject -- https://master.php.net/note/reject/105095
Search -- https://master.php.net/manage/user-notes.php