note 69382 added to function.array-rand
| From: | JS at osu1 dot php dot net | Date: | Mon, 04 Sep 2006 10:07:50 +0000 |
| Subject: | note 69382 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-116649@lists.php.net to get a copy of this message | ||
I wanted to write something that picks a random entry from a 1column-MySQL database - simply Post Of
The Moment (potm). I know there surly are many better ways to do it, but I
m rather new to PHP
:) Anyway, its simple and no-problem working code.
Of course I assume your DB exists and you always have something in it.
@$link = MySQL_Connect("localhost", "username", "password"); //connect
to mysql
mySQL_Select_DB("database"); //..to DB
@$potms = MySQL_Query("SELECT * FROM potm"); //now we get all from our table and store it
MySQL_Close($link); //there`s no need for connection, so we should close it
$potm_array = ''; //sets variables to "zero" values
$i = 0;
while ($entry = MySQL_Fetch_Array($potms)) //now we go through our DB
{
$potm_array[$i] = $entry; //our temporary array from which we will random pick a field key
$i++; //now we increment our field key
}
$potm_id = array_rand($potw_array); //picks a random key from array
$potm = $potm_array[$potm_id]['name_of_the_field']; //now we have stored our Post Of The
Moment in $potm
..hope this helps
----
Server IP: 212.24.129.110
Probable Submitter: 195.70.138.98
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- https://master.php.net/note/edit/69382
Del: integrated -- https://master.php.net/note/delete/69382/integrated
Del: useless -- https://master.php.net/note/delete/69382/useless
Del: bad code -- https://master.php.net/note/delete/69382/bad+code
Del: spam -- https://master.php.net/note/delete/69382/spam
Del: non-english -- https://master.php.net/note/delete/69382/non-english
Del: in docs -- https://master.php.net/note/delete/69382/in+docs
Del: other reasons-- https://master.php.net/note/delete/69382
Reject -- https://master.php.net/note/reject/69382
Search -- https://master.php.net/manage/user-notes.php