~/drupal/drupal-code-run-database-query-fetch-active-user-details-count-pagination.md

Drupal Code to run Database Query to Fetch Active User Details, Count, Pagination

2 min readDecember 30, 2021by Gorav Singal#drupal
// TL;DR

Use Drupal entityQuery to fetch active users with pagination, then serialize and write the results to a JSON file.

Drupal Code to run Database Query to Fetch Active User Details, Count, Pagination

Introduction

This post shows code to run database query to fetch active user details, its count, with pagination and write its result json to a file.

Get Active Users

We will use \Drupal::entityQuery to run database query

$query = \Drupal::entityQuery('user')
    ->condition('status', '1');
$uids = $query->execute();

foreach ($uids as $uid) {
	$user = user_load($uid);
  print_r($user);
}

Above code will just print the result on console or browser.

Get Active Users with Pagination

If your users count is huge, We should use pagination. Else, we may get out of memory kind of errors. Or, database may become unresponsive.

$query = \Drupal::entityQuery('user')
    ->condition('status', '1')
    ->range(0, 1000);
$uids = $query->execute();

foreach ($uids as $uid) {
	$user = user_load($uid);
  print_r($user);
}

Notice the range(offset, count) function. Assume you have 5000 users, you will run above query 5 times, with following range parameters.

range(0, 1000)
range(1000, 1000);
range(2000, 1000);
range(3000, 1000);
range(4000, 1000);

Get Count of Users Based on Condition

//get total users
$query = \Drupal::entityQuery('user')
    ->condition('status', '1');

$total_users = $query->count()->execute();
print_r($total_users);

You can also run above query to get the total count of users, based on query condition.

Get Active Users and Write its JSON to a File

We may want to convert the output to JSON and write it to file.

$query = \Drupal::entityQuery('user')
    ->condition('status', '1')
    ->range(0, 1000);
$uids = $query->execute();

$baseFolder = '/your_folder/';

foreach ($uids as $uid) {
  $user = user_load($uid);
  $data = \Drupal::service('serializer')->serialize($user, 'json', ['plugin_id' => 'entity']);

  $filename = $baseFolder.$uid.'.json';
  print('<br/>Writing to file: '.$filename);
  file_put_contents($filename, $data); 
}

We first need to convert the object to json, it is done by:

\Drupal::service('serializer')->serialize($user, 'json', ['plugin_id' => 'entity'])

Then, we are creating a separate file based on uid of user.

Also see: Drupal Code to Fetch User Accessed Website within Last One Year

$ 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 Mysql Query to Fetch User Field Details and its Alias

Drupal Mysql Query to Fetch User Field Details and its Alias

Introduction In this posr, we will see how to prepare mysql query to fetch user…

Drupal DB Query Code to Fetch Active Users and Accessed Website Within last One Year

Drupal DB Query Code to Fetch Active Users and Accessed Website Within last One Year

Introduction Here, we will see the drupal code to fetch all the active users…

Drupal 8 - How to Theme Form and its Fields with reordering fields

Drupal 8 - How to Theme Form and its Fields with reordering fields

Introduction In this post, we will see how to theme form and its fields…

Drupal 8 - How to create a Page with admin access and create its menu entry in Reports (No Coding)

Drupal 8 - How to create a Page with admin access and create its menu entry in Reports (No Coding)

Introduction I needed a report page, where I wanted to have some information…

Drupal 7 - Code for Exporting all your content nodes in json files

Drupal 7 - Code for Exporting all your content nodes in json files

Introduction When I migrated all of my drupal-7 website to drupal-8, I wrote…

Drupal: How to detect country and redirect to country specific website by using Cloudflare

Drupal: How to detect country and redirect to country specific website by using Cloudflare

Introduction Assume you have a drupal website and using cloudflare. You are…

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…