Share icon
how to use db_query in drupal8

Hey again, again we are come up with drupal8 useful functional to use.

today we see how we can use db_query in your custom module to fetch the complicate data, avoid the joins and conditions. db_query usually use to fastest way to doing these kind of jobs. let check below how you can use it

As we know drupal8, we need to database connection we need at the class in our custom module but you can add the class inline as well, like this 

$db = \Drupal\Core\Database\Database::getConnection();

you can put these line, no need add the class, I am not recommeded that, if you follow the standart way that we better. I am showing this to you because of this tutorial direct piece of code.

$db = \Drupal\Core\Database\Database::getConnection();
$query = $db->query("SELECT * FORM users");
$users= $query->fetchAll();

Just above three lines of code can run your compicate query into simple form.

All data loads into $users variable and you can do whatever you like to perform by the code.

Thanks for reading, hopes it helps

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.