2
    $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

2
  • What error message do you get? Commented Jun 16, 2018 at 18:55
  • Warning: mt_rand() expects parameter 1 to be integer, object given Commented Jun 16, 2018 at 18:57

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you should give the columns aliases, so they have more reasonable names.
1

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

Comments

0

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.

Comments

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.