-1

I'm trying to have my webpage select one random post from a database but it keeps returning an error. The error refers to the 3rd query as a bool rather than an object so there's something wrong with the code. I just don't know what. P.S I'm aware that the rest of the code may be sloppy, just need help with the mt_rand function.

<?php include('enter-message.php');
$query= $connect->prepare("SELECT MAX( id ) AS 'max_id' FROM userinfo")or die(mysqli_error($connect));;
$query->execute();
$query->bind_result($maximum);
while($query->fetch()){
//print_r($maximum);
}

$query= $connect->prepare("SELECT MIN( id ) AS 'max_id' FROM userinfo")or die(mysqli_error($connect));;
$query->execute();
$query->bind_result($minimum);
while($query->fetch()){
//print_r($minimum);
}

$request=$connect->prepare('SELECT * FROM userinfo ORDER BY mt_rand($minimum,$maximum) LIMIT 1');
if($request->execute()){
    while($request==$secret){
        echo("<div class='secrets-box'>");
        echo($secret['nickname']);
        echo($secret['secret']);
        echo("</div>");
    }
Newbie19
  • 13
  • 2
  • 5
    `mt_rand` is a PHP function, not a MySQL function. https://stackoverflow.com/questions/32236915/is-there-a-similar-function-like-mt-rand-for-mysql might be of some help for you – aynber Dec 22 '21 at 13:23
  • 1
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Dec 22 '21 at 13:50
  • Be aware that a random number in the (min, max) range may not match an user someewhere down the road. When entries are deleted, there will be gaps. – Markus AO Dec 22 '21 at 18:16

2 Answers2

1

You should try this:

$request = $connect->prepare( 'SELECT * FROM userinfo ORDER BY ' . mt_rand($minimum,$maximum) . ' LIMIT 1' );

Better yet:

$rand = mt_rand($minimum,$maximum);
$request = $connect->prepare( 'SELECT * FROM userinfo ORDER BY %s LIMIT 1', $rand );
FS-GSW
  • 152
  • 9
1

You can use mysql rand() function :

'SELECT * FROM userinfo ORDER BY rand() LIMIT 1'

will return a random row from userinfo

Jayvee
  • 10,670
  • 3
  • 29
  • 40