Using Select Statement in Drupal 7

You are here

Wakensys - Drupal

<?php
 
/*

 * Drupal way of Selecting (Fetching) data from the database tables

 * Abdul@wakensys.com

 * Replace the values with your required values within {}

 * Drupal 7

 */
 

  = db_select('node', 'n'); // base Table to use SELECT

  ->join('{table_name}', 't', 'n.nid = t.nid');  // the Table that you would like to Join

 

    ->fields('n', array('nid', 'title', 'uid')) // fetch for fields nid, title and author from table node

    ->fields('t', array('{field1}', '{field2}')) // fetch for fields {field1} and {field2} fromt table {table_name}

    ->condition('n.nid', , '=') // being the value you pass through the function

    ->condition('t.{field1}', , '=') // being the value you pass through the function

    ->condition('n.type', 'page') //  only content type Basic Page

    ->condition('n.status', 1); // only fetch Published content

 

  = ->execute();

  

  foreach ( as ) {

    // Do something with each

    /*

     *

     */

 

  }  // end foreach

 
?>