user4586206
user4586206

Reputation:

Random data mysql

I have table in mysqli database now i want to get 1 result random This is code mysql

$cid = $_GET['id'];

$ans = $db->query("select * from result where cat_id='$cid' limit 1");
$rowans = $ans->fetch_object();

echo"
<h4>".$rowans->title."</h4><br>
<img src='".$rowans->img."' style='width:400px;height:300;' />
<p>".$rowans->desc."</p>";

in this code i get 1 result but not random always gives me the same result

Upvotes: 0

Views: 39

Answers (2)

Galz
Galz

Reputation: 6842

LIMIT orders the rows by the primary key of the table, so you always get the same one (the "first" row according to that key).

Try:

SELECT * FROM result WHERE cat_id='$cid' ORDER BY RAND() LIMIT 0,1;

You can think of it this way: it first orders the results by a random order, then picks the first one.

Upvotes: 1

Rafael
Rafael

Reputation: 7746

SQL:

SELECT * 
FROM result 
ORDER BY rand()
LIMIT 1

Upvotes: 2

Related Questions