~/drupal/29-drupal-helpful-codes-database-queries.md

Drupal Helpful codes for database queries

2 min readMarch 18, 2018by Gorav Singal#drupal#drupal-code#scripting
// 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);

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

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

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…