drupal|March 18, 2018|2 min read

Drupal Helpful codes for database queries

TL;DR

Handy Drupal 7 PHP code snippets for querying nodes, taxonomy terms, and other database operations used in templating and automation.

Drupal Helpful codes for database queries

Being a drupal user from last around 5 years, I used to know small codes for drupal. These codes helps in many ways, in templating, or in writing custom automation etc.

To get all the Node Id's (nid) from a content type

$query = db_select( 'node', 'n' );
  $query
    ->condition( 'n.type', '' )
    ->fields('n', array('nid'));
  $result = $query
     ->execute()
   ->fetchAll();

foreach( $result as $row ) { print_r($row); }

To get all the Node Id's and Titles from a content type

$query = db_select( 'node', 'n' );
  $query
    ->condition( 'n.type', '' )
    ->fields('n', array('nid', 'title'));
  $result = $query
    ->execute()
   ->fetchAll();

foreach( $result as $row ) { print_r($row); }

To get Node title from a single Node without loading the node

Note: You can get all the attributes from a node by loading a node, by using php code: node_load(nid). But, it is very heavy operation. In many cases, you do not want to load complete node.

function getTitle($nid) {
  $query = db_select( 'node', 'n' );
  $query
      ->condition( 'n.nid', $nid)
      ->fields('n', array('title'));
    $result = $query->execute();
    
    return $result->fetchObject()->title;
}

To get random nodes from a content type and fetch only node id and title, and do not fetch all nodes

  $contentType = 'article';
  $rangeFrom = 0;
  $number = 4;
  $query = db_select('node', 'n');
      $query->condition('n.status', NODE_PUBLISHED);
      $query->condition('n.type', $contentType);

  $info = $query
  ->fields('n', array('nid', 'title'))
    ->orderBy('n.changed', 'DESC')
    ->range($rangeFrom, $number)
    ->execute()
    ->fetchAll();
print_r($info);

Get a node based on a field value

Example: If my content type has a field: videoId. Find out if this content type has any node with this particular videoIdas value.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('my_field_name', 'value', 'my_required_field_value', '=');

$result = $query->execute();

print_r($result);

Related Posts

Drupal: How to block a user by email programatically

Drupal: How to block a user by email programatically

Many times, while administering your drupal website, you must have encountered…

List all the Node ids which do not have images from my domain

List all the Node ids which do not have images from my domain

I use drupal-7 in my website. I used to write articles and put images in that…

Drupal Code: Fetch Link, Title, Category names, tag names from every article

Drupal Code: Fetch Link, Title, Category names, tag names from every article

See the code below: The output will be 4 columns separated by comma. You can…

Drupal 7: How to save a node programmatically and add an image field from a public URL

Drupal 7: How to save a node programmatically and add an image field from a public URL

Note: I have public URLs of these images, which I want to save. return…

Docker image for Drupal 7, and Php extension MongoDB installed.

Docker image for Drupal 7, and Php extension MongoDB installed.

You have drupal 7 image from docker hub, and want to connect tomongo db via php…

How to add alt attribute of images in all of my drupal articles or other content type

How to add alt attribute of images in all of my drupal articles or other content type

I have a custom content type, and there are around 2000 number of nodes in my…

Latest Posts

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…