Page 1 of 1

hi echoing a radom sql value

Posted: Fri May 26, 2006 11:20 am
by reecec
Hi if i have this radom sql code

how would i get it to give me the values so i could echo the radom value



SELECT column FROM table
ORDER BY RAND()
LIMIT 1


thanks reece

Re: hi echoing a radom sql value

Posted: Fri May 26, 2006 12:06 pm
by RobertGonzalez

Code: Select all

<?php
$sql = "SELECT column 
        FROM table 
        ORDER BY RAND() 
        LIMIT 1";

if (!$result = mysql_query($sql))
{
    die("There was an error in the query $sql: " . mysql_error());
}

while ($row = mysql_fetch_array($result))
{
    echo $row['column'] . ' is the random string returned from the table...';
}
?>

Posted: Fri May 26, 2006 12:21 pm
by Flamie
useing mysql_fetch_array or object to get just 1 field isnt necessary!

Code: Select all

$query ="SELECT column
        FROM table
        ORDER BY RAND()
        LIMIT 1"; 
$result = mysql_query($query) or die("error");
$field = mysql_result($result,0);

Posted: Fri May 26, 2006 12:48 pm
by onion2k
mysql_result() is PHP's slowest ever function. It's good practise to never use it because it's really so bad.

Posted: Fri May 26, 2006 12:56 pm
by RobertGonzalez
Flamie wrote:useing mysql_fetch_array or object to get just 1 field isnt necessary!
I have used the exact same code I posted above with absolutely no performance issues at (mysql_fetch_array). Yes, it is only one result, but it is still fast and manages to do what is needed without a lot of overhead (one loop through an array of one values). It is also consisten with a lot of other code in the scripts I use so it maintains the flow of development I follow. Not to mention, it is a straight forward, easy to understand snippet without any performance issued like mysql_result().

PS Thanks onion for the bit about mysql_result(). That is a handy piece of info to have. Even the manual page mentions that it is a slow function in some instances.

Posted: Fri May 26, 2006 1:45 pm
by Flamie
=O I didnt know it was slow :x hehe, now I know at least (=

Posted: Fri May 26, 2006 3:24 pm
by reecec
thanks all


sorry can some one tell me why my (rand 1, 2)

always comes out as the first number i put


thanks reece

hi

Posted: Fri May 26, 2006 3:25 pm
by reecec
sorry rand (1,2)

Posted: Fri May 26, 2006 3:37 pm
by RobertGonzalez
Have you looked at the MySQL manual for the RAND() function and its uses?