Darkkz
Darkkz

Reputation: 436

Select a random value from an array after a selection from database

I'm trying to get a random value from an array that is populated with data from the database. I'm selecting some products from the DB and display them on the front page, but i need to display different (random) producs everytime the page is reloaded.

$row = mysql_query("SELECT * FROM anunt WHERE lichidareStoc = 0 ORDER BY anuntID DESC") or die(mysql_error());
$row2 = mysql_fetch_assoc($row);

So, i think that $row2 is now an array, and has all the infos that i selected previously from the database. How do i select a random 'row' from that array now?

Thanks

Upvotes: 0

Views: 1839

Answers (3)

bpoiss
bpoiss

Reputation: 14003

You are looking for array_rand, see: http://php.net/manual/en/function.array-rand.php

Example:

$rand_key = array_rand($row2);
echo $row2[$rand_key]; // your random

You could also directly select a random row from your DB:

SELECT * 
FROM anunt
WHERE lichidareStoc = 0
ORDER BY rand() 
LIMIT 1

But be aware, this will reduce your performance, especially on bigger tables.

Side Note: mysql_* function are deprecated, use mysqli_* instead.

Upvotes: 2

Orangepill
Orangepill

Reputation: 24645

You will first want to populate an array of your results

$row = mysql_query("SELECT * FROM anunt WHERE lichidareStoc = 0 ORDER BY anuntID DESC") or die(mysql_error());
$rows = array();
while($rec =  mysql_fetch_assoc($row)){
    $rows[] = $rec;
}

Then you can select a random item using array_rand

$random = $rows[array_rand($rows)];

Upvotes: 0

Ryckes
Ryckes

Reputation: 34

If you want to select a random entry, you could do something like this:

$myRows=array();
$row = mysql_query("SELECT * FROM anunt WHERE lichidareStoc = 0 ORDER BY anuntID DESC") or die(mysql_error());
while($row2 = mysql_fetch_assoc($row))
    $myRows[]=$row2;

$randomEntry=$myRows[array_rand($myRows)];

If you wanted a random field of that entry though, you should use array_rand like Bernhard Poiss pointed out.

$row = mysql_query("SELECT * FROM anunt WHERE lichidareStoc = 0 ORDER BY anuntID DESC") or die(mysql_error());
$row2 = mysql_fetch_assoc($row);
$randomField=$row2[array_rand($row2)];

Upvotes: 0

Related Questions