Query result to display in Views i have created a custom view. its just showing nodes of a particular type. Now i want to do something with it. I am writing a SQL query:

global $user;
$query = db_select('challenges','c');
$query-&gt;join('node','n','n.nid = c.cid');
$query-&gt;join('field_data_body','f','n.nid = f.entity_id');
$query-&gt;join('field_data_field_challenge_pic', 'fp','n.nid = fp.entity_id');
$query-&gt;join('file_managed','fm','fp.field_challenge_pic_fid = fm.fid');
$query-&gt;fields('n',array('nid','title','created'))
      -&gt;field('f',array('f','body_value'))
      -&gt;field('fp',array('fm','uri'))
      -&gt;condition('c.cid','$user-&gt;uid','=');
$result = $query-&gt;execute(); 


Where should i place this query in my custom module and how can i get my view to display this? I tried writing this code in a tpl file for the view and then did print_r and render() but no effect. I think it should be done through views.
write code in your module like this way.

Declaring the block

function mymodule_block_info() {
  $blocks['current_posts'] = array(
    'info' =&gt; t('Current posts'), //The name that will appear in the block list.
    'cache' =&gt; DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}


Retrieving data

    function mymodule_contents(){
      $query = db_select('challenges','c')
$query = db_select('challenges','c');
$query-&gt;join('node','n','n.nid = c.cid');
$query-&gt;join('field_data_body','f','n.nid = f.entity_id');
$query-&gt;join('field_data_field_challenge_pic', 'fp','n.nid = fp.entity_id');
$query-&gt;join('file_managed','fm','fp.field_challenge_pic_fid = fm.fid');
$query-&gt;fields('n',array('nid','title','created'))
      -&gt;field('f',array('f','body_value'))
      -&gt;field('fp',array('fm','uri'))
      -&gt;condition('c.cid','$user-&gt;uid','=')
        -&gt;execute(); 
      return $query;  
    }


Generating block content

function mymodule_block_view($delta = '') {
  switch($delta){
    case 'current_posts':
      $block['subject'] = t('Posts');
      if(user_access('access content')){
        //Use our custom function to retrieve data.
        $result = mymodule_contents();
        //Array to contain items for the block to render.
        $items = array();
        //Iterate over the resultset and format as links.
        foreach ($result as $post){
          print $post;
        }

        if (empty($items)) { //No content in the last week.
          $block['content'] = t('No posts available.');  
        } 
        else {
          //Pass data through theme function.
          $block['content'] = theme('item_list', array(
            'items' =&gt; $items));
        }
      }
    return $block;
  }

}