3 random results from one table

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
CodeMama
Forum Newbie
Posts: 9
Joined: Fri Nov 07, 2008 12:28 pm

3 random results from one table

Post by CodeMama »

I have to get 3 random results to populate a 3 column table, so far I can only get one random result, I have tried to make more $title2 like that but it will just pull the same one, I think there is a math thing I'm missing here, I also have to count the times these blurbs appear...need guides please , so far I just keep ending up with endless loops that make the page time out....
here is my code so far:
I have also tried changing the sql statement to $sql ="select * from textads ORDER BY RAND() LIMIT 0,3"; but then just get 3 tables all still with the same blurb in the columns so maybe I am outputting it the wrong way?

Code: Select all

 
 
 
<?php include 'inc/dbconnOpen.php';
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
 
$sql ="select * from textads ORDER BY RAND() LIMIT 0,1";  /* query */
$result= mysql_query($sql);
 
$num=mysql_num_rows($result);
 
mysql_close();
 
echo "<b><center>Database Output</center></b><br><br>";
 
$i=0;
while ($i < $num) {
 
$href=mysql_result($result,$i,"href");
$blurb=mysql_result($result,$i,"blurb");
$title=mysql_result($result,$i,"title");
 
 
 
        
        
        
echo "<table border= 1 height=90px width=468px bgcolor=#cccccc><tr><td>$title<br>$blurb<br>
<A HREF='$href'>$href</a></td><td>$title<br>$blurb<br>
<A HREF='$href'>$href</a></td><td>$title<br>$blurb<br>
<A HREF='$href'>$href</a></td></tr></table>";
 
$i++;
}
 
?>
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: 3 random results from one table

Post by Apollo »

A query like "SELECT * FROM table ORDER BY RAND() LIMIT 0,3" should certainly give you 3 random, unique rows.

Instead of using mysql_result, try a function like mysql_fetch_assoc.
Post Reply