简体   繁体   中英

Trying to get a random number from db php doesn't work

    $total_numMIN = mysqli_query($con,"SELECT MIN(id) FROM view_rating");
    $total_numMAX = mysqli_query($con,"SELECT MAX(id) FROM view_rating");
     $random_no = mt_rand($total_numMIN, $total_numMAX);    
     print $random_no;

I'm trying to get a single number randomly generated from the smallest and largest numbers in my database. Right now the error I'm getting is

Warning: mt_rand() expects parameter 1 to be integer, object given in

I'm just not exactly sure why the results of the queries aren't integers

mysqli_query() returns a mysqli_result which is an object and not the numbers you are expecting. You need to get an array of results from your query. The MIN and MAX queries can also be combined into a single query.

$result = mysqli_query($con,"SELECT MIN(id) as min, MAX(id) as max FROM view_rating");

if($result) {
    $resultArray = $result->fetch_assoc();
    $random_no = mt_rand($resultArray['min'], $resultArray['max']);    
    print $random_no;
}

There may be a cleaner way to do this. I haven't used PHP in a long time.

change your code like this

$total_numMIN = mysqli_fetch_assoc(mysqli_query($con,"SELECT MIN(id) as min,MAX(id) as max FROM view_rating"));
$random_no = mt_rand($total_numMIN['min'], $total_numMAX['max']);    
print $random_no;

because mysqli_query just give you a object. you have to fetch data as an associative array and then you can use it into mt_rand hope this will work

The mysql_query returns a result - and not a value.

From the documentation on the function: http://php.net/manual/en/mysqli.query.php

Return Values

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM