user1483138
user1483138

Reputation: 67

How to prevent selecting deleted IDs when selecting random row from sql table

I want to select random rows from a product database by their unique id`s. I need 3-4 random products on every page...

This is how i started

$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `products` ");
$offset_row = mysql_fetch_object( $offset_result ); 
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `products` WHERE id = $offset LIMIT 1" );
$n=mysql_num_rows($result);

if ($n>0){
    while($row = mysql_fetch_array($result)){ 
        $id = $row["id"];
        $cod_produs = $row["cod_produs"];
        $nume_produs = $row["nume_produs"];
        $titlul_paginii = $row["titlul_paginii"];
        $nume_intermediar = str_replace (" ", "-", $nume_produs);
        $nou_nume_produs = strtolower($nume_intermediar);
        $detalii = $row["detalii"];
        $seo_descriere = $row["seo_descriere"];
        $materiale = $row["materiale"];
        $numere = $row["numere"];
        $pret = $row["pret"];
        $categorie = $row["categorie"];
        $subcategorie = $row["subcategorie"];
        $data_adaugare = strftime("%b %d, %Y", strtotime($row["data_adaugare"]));

    }

echo ("The id of the product is ".$id." and his name is ".$nume_produs);

    };
  ?>

The problem is that my code returns ids that i have deleted over time... how do i prevent doing that?

And how i can return 3 or 4 unique id's at once, and am open to better ways of doing this?

Upvotes: 0

Views: 198

Answers (2)

dani herrera
dani herrera

Reputation: 51715

The usualy way is:

SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;

You can read explanation at Selecting random record from MySQL database table.

For your code:

mysql_query( " SELECT * FROM `products` ORDER BY RAND() LIMIT 0,3" );

Edited due OP comment

Then, you can get a subset of data. Modifying your code:

$offset_result = mysql_query( "SELECT FLOOR(MAX(id) * RAND() - 1000) AS `offset` 
                               FROM `products` ");
$offset_row = mysql_fetch_object( $offset_result ); 
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `products` 
                         WHERE id between $offset and $offset + 1000
                         ORDER BY RAND() 
                         LIMIT 0,3" );

And the fast solution is to get 3 randoms ID's:

$randoms_id = '-1';
for($i=0;$i<3;$i++) {

  $id_result = mysql_query( " SELECT id FROM `products` 
                              WHERE id >= 
                                  (SELECT FLOOR( MAX(id) * RAND()) 
                                   FROM `products` ) 
                              ORDER BY id LIMIT 1;");
  $id_row = mysql_fetch_object( $id_result ); 
  $id = $id_row->id;

  $randoms_id = $randoms_id . ',' . $id;
}
$result = mysql_query( " SELECT * FROM `products` 
                         WHERE id in ($randoms_id);")

Upvotes: 3

Ghassan Elias
Ghassan Elias

Reputation: 2233

You have a mistake in your script, do this:

$offset_result = mysql_query("SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM `products`");
$offset_row = mysql_fetch_object($offset_result); 
$offset = $offset_row->offset;
$result = mysql_query("SELECT * FROM `products` LIMIT $offset, 1");
$n=mysql_num_rows($result);

But this will return only one record. you can get consecutive records or you have to run it many times.

$offset_result = mysql_query("SELECT COUNT(*) AS total FROM `products`");
$offset_row = mysql_fetch_object($offset_result); 

$total = (($offset_row->total) - 1);
$range_arr = range(0, $total);
shuffle($range_arr);
$off_1 = $range_arr[0];
$off_2 = $range_arr[1];
$off_3 = $range_arr[2];

$result = mysql_query(" (SELECT * FROM `products` LIMIT $off_1, 1)
                        UNION
                        (SELECT * FROM `products` LIMIT $off_2, 1)
                        UNION
                        (SELECT * FROM `products` LIMIT $off_3, 1)");
$n=mysql_num_rows($result);

Upvotes: 1

Related Questions