Get list of MySQL databases using PHP

MySQL has a built-in command to get a list of databases that can be accessed by the currently logged in user, and it is very easy to take this list and use it inside a PHP script.

First, let’s look at the command from inside the MySQL monitor ptogram. If you have any experience inside the MySQL monitor you have probably run the command SHOW DATABASES;. If not, below is what the output looks like.

show_databases.gif

Let’s say you want to get the list of available databases in a sorted list. You’d use something like the following.

PHP:
  1. $conn = mysql_connect(’server’, ‘username’, ‘password’);
  2. $rs = mysql_query(“SHOW DATABASES”);
  3. while ($row=mysql_fetch_row($rs))
  4. {
  5. $arr_databases[] = $row[0];
  6. }
  7. sort($arr_databases);
  8. print_r($arr_databases);

This will put all the available database names into an array and then sort them. The print_r line simply dumps the array so that you can see what it looks like. If you were really using this it is doubtful you’d include that line.

Security
It’s important to mention that you will only see the databases that you have access to with your login. The server may contain hundreds if not thousands of databases, but MySQL security will only allow you to know of the ones you have permission to view.

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

Leave a Reply