$stmt = $web_dbi->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
while($row=mysqli_fetch_array($result)){
$results[] = $row;
}
$randomNumber = mt_rand(0,($num_of_rows-1));
if($results[$randomNumber]['mysql_field']==anothervalue){
...
how do I access, at random, a given element of $results[]
? Is this syntax correct in this scenario?
Your code looks fine. I personally prefer using array_rand to select a random element from the array:
$random_value = $results[array_rand($results)];
shuffle($results);
$item_to_use = array_pop ($results);
Not the most efficient but uses fewer lines of code.
Alternativley, you can use sql query to get random result.
SELECT field1, field2, field3 FROM table_name ORDER BY RAND()
Or to get random array element from PHP array try this,
echo $results[mt_rand(0, $num_of_rows - 1)]['mysql_field'];