Using ORDER BY RAND () with multiple WHERE mysql clauses

I know that the order by rand () is not the fastest way to draw a random value from a database, but my database is small, and for now; I just want it to work! haha Here is my code:

include('includes/dbc.php');
$top_query = "SELECT * FROM top WHERE 'occasion_id =" . $occasion . "' AND 'temperature_id = " . $temperature . "' AND 'user_id = " . $user_id . "'ORDER BY RAND() LIMIT 1";
$top_result = mysqli_query($dbc, $top_query) or die (' The top SELECT query is broken.');
mysqli_close ($dbc);

while($row= mysqli_fetch_array($top_result)) {
    echo 'This top has an id of:' . $row['top_id']  . '<br> ';
    echo 'Does this top require pants?' . $row['needs_pants']  . '<br>';
    echo 'What\ the colour id of this top?' . $row['colour_id'] . '<br>';
    echo  $row['value'];
}

For some reason this just doesn't work, and I'll just show it empty when I try to start my array. It worked before I tidied up the rand () limit 1 "bit, but obviously I got every value instead of one random.

Can anyone see where I made a mistake? Many thanks!

+3
source share
1 answer

Your request is incorrect. He does not die, he simply does not return results.

Note the erroneous single quotes:

$top_query = "SELECT * FROM top WHERE 'occasion_id =" . $occasion . "' AND 'temperature_id = " . $temperature . "' AND 'user_id = " . $user_id . "'ORDER BY RAND() LIMIT 1";

, , MySQL (, PHPMyAdmin):

echo $top_query;

mysqli_error() mysqli_num_rows() .

, SQL :

$top_query = "SELECT * FROM top WHERE occasion_id = '" . $occasion . "' AND temperature_id = '" . $temperature . "' AND user_id = '" . $user_id . "' ORDER BY RAND() LIMIT 1";

:

+8
source

All Articles