PHP: Get a list of all MySQL databases using PDO.

This is a short tutorial on how to get a list of all MySQL databases using PHP’s PDO object. To do this, we will connect to MySQL and execute a “SHOW DATABASES” query.

Take a look at the following snippet:

In the code above:

  1. We connected to the MySQL server using the PDO class. Note that in this case, we omitted the database argument from the $dsn string in the constructor.
  2. Using the query function, we executed a “SHOW DATABASES” SQL statement. It is worth pointing out that you can also use the query “SHOW SCHEMAS”, as they are both synonyms of each other.
  3. We fetched the list of database names by using the fetchAll function in conjunction with PDO::FETCH_COLUMN.
  4. Finally, we looped through our array of database names and printed them out.

LIKE clause.

You can also search for a specific database by using a LIKE clause. For example, if you wanted to retrieve a list of all databases starting with “users_”, then you could do something like this:

In the query above, I used the LIKE clause with a wildcard operator.

Hopefully, you found this guide useful!

Related: Get a list of tables.

Facebook Comments