hyptos
hyptos

Reputation: 160

Symfony2 - Show all tables from database

I would like to retrieve all the tables of my database as a list.

i tried to do a "Show databases" on a query but as i'm not using a class I defined (entity) in symfony it's not working.

And with DQL :

   $em = $this->getDoctrine()->getEntityManager();
   $query = $em->createQuery(
        'show databases');

    $result = $query->getResult();

This error :

[Syntax Error] line 0, col 0: Error: Expected SELECT, UPDATE or DELETE, got 'show'

Any idea to help me ?

Upvotes: 6

Views: 12355

Answers (5)

Thomas Decaux
Thomas Decaux

Reputation: 22661

My 2 cents:

getContainer()->get('doctrine.dbal.default_connection')->getSchemaManager()->listTableNames()

This will give you an array of table names.

Upvotes: 5

kaiser
kaiser

Reputation: 22333

As mentioned in a different answer, you can use Doctrine\DBAL for that:

/** @type \Doctrine\DBAL\Connection $connection */
$connection = ...;

/** @type \Doctrine\DBAL\Schema\MySqlSchemaManager $sm */
$sm = $connection->getSchemaManager();

And then just list the tables as Array:

var_dump( $sm->listDatabases() );

Upvotes: 8

Alexandru Furculita
Alexandru Furculita

Reputation: 1373

You can add Doctrine DBAL to your project and it will give you the tools you need. You can list databases, tables from a database, columns from a table etc etc

More in Doctrine DBAL documentation: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/schema-manager.html

Upvotes: 4

MrGlass
MrGlass

Reputation: 9262

i have a couple cases where I need to use complex sql statements/functions that I just couldn't do in DQL. Luckily, Symfony2/doctrine provide a method to grab the current database connection and bypass doctrine entirely.

//get connection
$conn = $this->get('database_connection');
//run a query
$users= $conn->fetchAll('select * from users');

Be very careful when using this method, however. Since you are bypassing doctrine, you need to handle any security concerns like SQL injection yourself.

Upvotes: 4

Xnoise
Xnoise

Reputation: 522

Doctrine is a ORM, it is not intended to list all the databases. Beside that, usually for the current user you don't have the right to show all databases in the server, this can prove to be a big security breach.

Basicly, doctrine does not know how to interpret your query, you have to use a native query for this: Doctrine Native Query

Upvotes: 2

Related Questions