简体   繁体   中英

How to exclude unpublished nodes from db_query results?

How to exclude unpublished nodes via db_query?

I figured they are defined as

SELECT * FROM `node` WHERE status = '1'

but how to include that in the below drupal db_query?

function faq_search_find() {

  $term = strip_tags(drupal_substr($_POST['keyword'], 0, 100));

  $result = db_query("SELECT question, nid
  FROM {faq_questions}
  WHERE question LIKE :term
  ORDER BY question asc", array(':term' => '%%' . $term . '%%'));
  $string = "";

  while ($row = $result->fetchObject()) {
    $string .= "<a href='/" . drupal_get_path_alias('node/' . $row->nid) . "'>" . $row->question . "</a>";
  }

  echo $string;
  exit;
}

Could the searh be combined based on nid within the node table or would a better approach be to filter them out with a Drupal command in the while loop?

Thanks for your help.

You can join to the node table, or you can use an EFQ as comments above suggest. But here's the SQL

   $result = db_query("SELECT question, nid
     FROM {faq_questions} F1
     INNER JOIN {node} N1
     ON F1.nid = N1.nid AND N1.status = 1
     WHERE question LIKE :term
     ORDER BY question asc", array(':term' => '%%' . $term . '%%'));

In case you wanted an actual explanation as to why you should use an EFQ... while there are often cases where SQL is the right tool for the job, this really is not one of those. By writing raw SQL, you are tying your logic directly to database schema over which you have no control. If a future module update were to alter the schema, you would have broken code that would need updating.

While the node table is not likely to change in any significant way, the faq_questions table certainly could.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM