Jump to content

Recommended Posts

I would like this to select a random record from MySQL database table.

How could I do this?

 

<?php
require_once("../includes/db_config.php");

$db = mysql_connect(DB_SERVER, DB_USER, DB_PASS);

if($db) {
	if(mysql_select_db("", $db)) {
		$sql = "SELECT id, imageurl1, title, county, rent, description FROM apartments WHERE date_created = (SELECT MAX(date_created) FROM apartments)";
		$result_set = mysql_query($sql, $db);
		if($result_set && mysql_num_rows($result_set) == 1) {
			$latest_listing = mysql_fetch_assoc($result_set);
		}
	}
}
?>

Link to comment
https://forums.phpfreaks.com/topic/266793-from-max-to-random/
Share on other sites

$sql = "SELECT id, imageurl1, title, county, rent, description FROM apartments WHERE date_created = (SELECT MAX(date_created) FROM apartments) ORDER BY RAND() LIMIT 1";
$result_set = mysql_query($sql, $db);
if($result_set && mysql_num_rows($result_set) == 1) {
$latest_listing = mysql_fetch_assoc($result_set);
}

Link to comment
https://forums.phpfreaks.com/topic/266793-from-max-to-random/#findComment-1367703
Share on other sites

Yes. You're trying to get a random record from a results set that only contains one record. Obviously, the "random" record will always be the only one that was selected. Also, see the link in my signature for reasons why 'ORDER BY RAND()' isn't a good idea, and suggestions on better ways to do it.

Link to comment
https://forums.phpfreaks.com/topic/266793-from-max-to-random/#findComment-1367710
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.