1

I have the following code to pull a random value from a database.

$result = mysqli_query($con,"SELECT column1 FROM table1
ORDER BY RAND()
LIMIT 1");

while($row = mysqli_fetch_array($result))
{
 echo $row['column1'];
 echo "<br>";
}

At the moment I only have about 10 values in total. Sometimes they appear more than once in a row upon refresh.

Can the query be amended to show a random value that is not the current value?

5
  • Random means repeated values some times. What you want is not random. Commented Jun 12, 2013 at 22:40
  • @PaulProgrammer: Can you predict the order? Commented Jun 12, 2013 at 22:42
  • Random is not the same as unpredictable either. I can roll a die repeatedly and if the result is truly random, it may roll 6 more than once in a row (in fact, it might be 4 or more times in a row) and still be random and unpredictable. Commented Jun 12, 2013 at 22:48
  • Anyway, if you want unpredictable, but nonrepeated values, you store the id for the last one generated and add it as an exclusion to your while clause. Commented Jun 12, 2013 at 22:50
  • Thanks guys. Interesting discussion! Commented Jun 22, 2013 at 15:34

1 Answer 1

1

in order to do that you need to somehow remember the last row. Then do something like this

$result = mysqli_query($con,"SELECT column1 FROM table1
where id_of_your_row != ".mysqli_real_escape_string($id_of_your_last_row)."
ORDER BY RAND()
LIMIT 1");

For remembering the last row, you could use sessions.

Your whole code could look like this.

// sessions need to bestarted

$result = mysqli_query($con,"SELECT column1 FROM table1
where column1 != ".(isset($_SESSION["lastid"]) ? mysqli_real_escape_string($_SESSION["lastid"]) : '')." ORDER BY RAND()
LIMIT 1");

while($row = mysqli_fetch_array($result))
{
 echo $row['column1'];
 $_SESSION["lastid"] = $row['column1'];
 echo "<br>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't seem to pull out any values. Is there an obvious typo?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.