/**
 * Fetch a random N image(s) - optionally from a given term.
 */
function image_get_random($count = 1, $tid = 0) {
  if ($tid != 0) {
    $result = db_query_range(db_rewrite_sql("SELECT DISTINCT(n.nid), RAND() AS rand FROM {term_node} tn LEFT JOIN {node} n ON n.nid = tn.nid WHERE n.type='image' AND n.status = 1 AND tn.tid = %d ORDER BY rand"), $tid, 0, $count);
  }
  else {
    $result = db_query_range(db_rewrite_sql("SELECT DISTINCT(n.nid), RAND() AS rand FROM {node} n WHERE n.type = 'image' AND n.status = 1 ORDER BY rand"), 0, $count);
  }
  $output = array();
  while ($nid = db_fetch_object($result)) {
    $output[] = node_load(array('nid' => $nid->nid));
  }
  return $output;
}

Correct me if I'm wrong, but shouldn't the code read:

    $result = db_query_range(db_rewrite_sql("SELECT DISTINCT(n.nid), RAND() AS rand FROM {term_node} tn LEFT JOIN {node} n ON n.nid = tn.nid WHERE n.type='image' AND n.status = 1 AND tn.tid = %d ORDER BY rand", $tid), 0, $count);

(notice the changed location of the paren by $tid) db_rewrite_sql should be using $tid as a parameter. I'm also not sure why we need to call db_rewrite_sql on the else case?

Comments

joachim’s picture

I must admit I've no idea what db_rewrite_sql does, and the API page at http://api.drupal.org/api/function/db_rewrite_sql does nothing to enlighten me.
It does however say that the second parameter is the primary table, which is not what $tid is.
We'd need to pass in n, nid before we get to the $tid argument.
Why do we need to call db_rewrite_sql anyway?

One thing I'd say though is: views! I reckon once this patch http://drupal.org/node/220295 is tested and committed, we can think about removing the hardcoded blocks and supplying a couple of views instead. So it may be that this issue is moot.

OneTallShort’s picture

Status: Active » Closed (fixed)

Code was correct and I was confused as to what db_rewrite_sql was doing to the function.

joachim’s picture

So am I!
What does it do? care to share here? http://drupal.org/node/444624