0

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

5
  • If the input for $_GET['id'] Is always the same it's always the same result?! Commented Feb 21, 2015 at 0:18
  • 2
    be careful with SQL injection in your sql statement too. You should be using prepared statements. Commented Feb 21, 2015 at 0:19
  • Where is the error & can you correction my code please Commented Feb 21, 2015 at 0:34
  • Whenever you take form input and use it in an SQL statement, you leave yourself open to people putting malicious SQL code in the form input field. Such as DROP TABLE or something like that and then you lose all the data. To prevent this prepared statements are used. Check out php.net/manual/en/mysqli.quickstart.prepared-statements.php Commented Feb 21, 2015 at 0:47
  • php.net/manual/en/mysqli.prepare.php Commented Feb 21, 2015 at 0:49

2 Answers 2

2

SQL:

SELECT * 
FROM result 
ORDER BY rand()
LIMIT 1
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments