Custom Select statement in Drupal 7

Public

The Drupal way of using SELECT statement in Drupal 7

Get raw version
php
  1. <?php
  2.  
  3. /*
  4.  * Drupal way of Selecting (Fetching) data from the database tables
  5.  * Abdul@wakensys.com
  6.  * Replace the values with your required values within {}
  7.  * Drupal 7
  8.  */
  9.  
  10. $query = db_select('node', 'n'); // base Table to use SELECT
  11. $query->join('{table_name}', 't', 'n.nid = t.nid'); // the Table that you would like to Join
  12. $query
  13. ->fields('n', array('nid', 'title', 'uid')) // fetch for fields nid, title and author from table node
  14. ->fields('t', array('{field1}', '{field2}')) // fetch for fields {field1} and {field2} fromt table {table_name}
  15. ->condition('n.nid', $nid, '=') // $nid being the value you pass through the function
  16. ->condition('t.{field1}', $field1, '=') // $field1 being the value you pass through the function
  17. ->condition('n.type', 'page') // only content type Basic Page
  18. ->condition('n.status', 1); // only fetch Published content
  19.  
  20. $result = $query->execute();
  21.  
  22. foreach ($result as $record) {
  23. // Do something with each $record
  24. /*
  25.  
  26.   *
  27.  
  28.   */
  29. } // end foreach
  30.  
  31. ?>

Comments

timonweb's picture

There are lots of empty rows, please fix it to make it look cleaner.

abdulqadir028's picture

I just wanted to make sure this is used as a guideline that's why I added this way. :(

timonweb's picture

I don't mean "Do something with each $record" part. That is ok. I'm talking about empty lines. For example: there is a code in line 15, and line 16 is empty, then you have code in line 17 and line 18 is empty and so on :) Looks like a formatting error :)