Drupal 7 – Sort by random when using db_select()

The following example is base on the database table i created previously.
Drupal 7 – Insert database record on module installation

We can add the orderRandom() to sort the records randomly. Here is an example.

function _get_random_color() {
  $id_color = db_select('eureka_variables', 'ev')
    ->fields('ev', array('variable_value'))
    ->condition('variable_key', 'COLOR', '=')
    ->range(0,1)    // Limit the result set by 1 record only
    ->orderRandom() // Sort by random
    ->execute()
    ->fetchAssoc();
  
  return $color['variable_value'];
}

 

Done =)

Reference: Drupal API – DatabaseSelectTestCase::testRandomOrder

2 thoughts on “Drupal 7 – Sort by random when using db_select()”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.