hi echoing a radom sql value
Moderator: General Moderators
hi echoing a radom sql value
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
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
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: hi echoing a radom sql value
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...';
}
?>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);- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
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().Flamie wrote:useing mysql_fetch_array or object to get just 1 field isnt necessary!
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.
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA