I want to execute SHOW TABLES in Drupal 8. In Drupal 7, I would use db_query("SHOW TABLES"), which is deprecated in Drupal 8.

What should I use for Drupal 8?

  • 1
    Note that this is pretty specific to MySQL. – mradcliffe Apr 19 '16 at 21:31

As quick replacement for queries on the database Drupal uses by default, you can use the following code.

use Drupal\Core\Database\Database;

$db = Drupal::database();
$result = $db->query("SHOW TABLES");

Keep in mind that:

  • db_query() will not be removed before Drupal 9 goes off; you can still use it, even if it is preferable to refactor your code to be more object oriented
  • The code I shown should be used in legacy procedural code; when possible, you should consider refactoring it to be object oriented and use Drupal 8 services and Dependency Injection Container
| improve this answer | |

You can still run arbitrary queries against the database. db_query is deprecated because it does not go well with the dependency injection pattern found elsewhere in D8.

All you need to do is getting the database object.

Default database

This should fit almost everyone, unless you are trying to run the query on a different connection.

$db = \Drupal::service('database');
$result = $db->query('SHOW TABLES'); // You can run the good old fetchAll(), etc on the $result now.

Other databases

If you want to run the query on a different database connection, just get the service spawn, and you can run query() on it.


I could find several examples from the Backup and migrate module's MySQLiSource class.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.