I asked this question yesterday and received an easy solution, but it was about ORDER BY rand(), which I was told was inefficient for large tables. I searched the web and found this a much more efficient method:
- Get the total number of rows in the table:
$rows
- Use
mt_rand
to set$row1_id
as a random number between 1 and the total number of rows:$row1_id = mt_rand(1,$rows)
- Use
mt_rand
again to set$row2_id
as a random number between 1 and the total number of rows:$row2_id = mt_rand(1,$rows)
- Run queries to select random rows, i.e.
mysqli_query($conn,"SELECT * FROM photos WHERE photo_id=$row1_id")
mysqli_query($conn,"SELECT * FROM photos WHERE photo_id=$row2_id")
However, I need to make sure that $row1_id
!= $row2_id
(the randomly generated numbers must be different from each other). I tried using an if statement but it only lessened the chances of the numbers being the same, but it was still possible.
Any easy solution to this one?