1

Im trying to display a random record from my table but with no luck this is what I have upto. This is coded in PHP

$range_result = mysql_query("SELECT MAX() AS max_id , MIN() AS min_id FROM pages");
$range_row = mysql_fetch_object( $range_result ); 
$random = mt_rand($range_row->min_id , $range_row->max_id);
$result_random = mysql_query( "SELECT * FROM pages WHERE id >= $random LIMIT 0,1");
echo $result_random;

Wondering if this is an obvious mistake? I have connected to the database fine.

JB

JB UCL
  • 165
  • 3
  • 15

3 Answers3

5

You should do this with straight SQL with a mysqli_multi_query for performance:

// First query gets the random ID, second gets the associated row
$sql = "SELECT @id:=FLOOR(RAND()*(MAX(id) - MIN(id))) + MIN(id) FROM pages; 
        SELECT * FROM pages WHERE id = @id;"

// Create a mysqli object and execute the multi-query
$mysqli = new mysqli($host, $user, $pass, $db_name);
$mysqli->multi_query($sql);
$result = $mysqli->store_result();

// Grab the first row from the first resultset
if ($row = $result->fetch_assoc()) {
    print_r($row);
}
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50
1

Why don't you just use rand():

"SELECT * FROM pages ORDER BY RAND() Limit 1"

But to answer, what is the MIN and MAX selecting if not defined? Should you perhaps try:

"SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM pages"

And I don't think you need the offset in the limit. So just LIMIT 1 would probably be fine.

As the comments state, RAND() might be slow for larger data sets, but in many cases this is not a problem and the lag is minimal unless you have an exceptional amount of data. Read frank's link to see details. Personally, though, I've never really had a problem on RAND() speed.

And as Michael said, you should probably try to fetch the results before echoing what you believe to be the result set.

And also, mysql_ functions are deprecated. You should switch to mysqli or PDO

Kai Qing
  • 18,793
  • 5
  • 39
  • 57
0

While you would be much better off ordering by RAND(), your method would work. Your problem is that you're trying to echo out a mysql result set. You need to do something like this after your code:

$row = mysql_fetch_assoc($result_random);
echo $row['field1'] . " " . $row['field2'];

Where field1 and field2 are names of columns in your table.

Michael
  • 402
  • 3
  • 8