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?
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
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.
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.
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