How do I write this PHP query the Drupal way (database abstraction)? I am using the code below to evaluate if a panel pane should display. I've read the docs on database abstraction, but I just don't really understand how to apply it. Of course, the dpm values are for debugging. 

(Just to be clear, this code is currently functioning exactly how I need it to, and I am not having any problems with panels itself. I just don't understand how to sanitize this the Drupal way to avoid injection.)

Any help would be appreciated. Here's the code:

// Gets NID of viewed node as well as the parent (passed by entity reference field)
$nid = $contexts['argument_entity_id:node_1']-&gt;data-&gt;nid;
$parent = $contexts['argument_entity_id:node_1']-&gt;data-&gt;field_webisode_series_reference['und'][0]['target_id'];

// Returns the 3 newest nodes with same parent as the view node
$recentNIDs = db_query("
    SELECT entity_id 
    FROM field_data_field_webisode_series_reference 
    WHERE field_webisode_series_reference_target_id = $parent 
    ORDER BY entity_id 
    DESC LIMIT 3
    ");
$result = $recentNIDs-&gt;fetchAll();

// Checks NID of the viewed node against NIDs of the 3 nodes above.
// If true, and NIDs match, then the block is displayed.
foreach ($result as $k =&gt; $v) {
    $nid2 = $v-&gt;entity_id;

    if ($nid2 == $nid) {
        $top3 = 1;
    }
}


// If $top3 is set, display. Else, do not.
if (isset($top3)) {
    dpm('TRUE', 'top 3?')
}

elseif (!isset($top3) {
    dpm('FALSE', 'top 3?')
}
I think that you can review this answer:


  If you use db_query() all the time without directly inserting
  variables, but using the arguments.


I hope information be useful.