drupal2 Min Read

Drupal Helpful codes for database queries

Gorav Singal

March 18, 2018

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);
Share

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

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI video generation went from “cool demo” to “usable in production” in 2024-202…

AI Models in 2025 — Cost, Capabilities, and Which One to Use

AI Models in 2025 — Cost, Capabilities, and Which One to Use

Choosing the right AI model is one of the most impactful decisions you’ll make…

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

Generating one image with AI costs between $0.002 and $0.12. That might sound…

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

Two years ago, AI coding meant one thing: GitHub Copilot autocompleting your…

AI Agents Demystified — It's Just Automation With a Better Brain

AI Agents Demystified — It's Just Automation With a Better Brain

Let’s cut through the noise. If you read Twitter or LinkedIn, you’d think “AI…

Supply Chain Security — Protecting Your Software Pipeline

Supply Chain Security — Protecting Your Software Pipeline

In 2024, a single malicious contributor nearly compromised every Linux system on…