Manage Databases on a Server by php

MySQL-related functions.

  • mysql_list_dbs() Used to list the databases on a MySQL server.
  • mysql_num_rows() Returns the number of rows in a result set.
  • mysql_tablename() Despite its name, can extract the name of a table or a database from a result.
The goal of this script is to list all the databases on the local MySQL server.
  1. Open a new file in your text editor and start a PHP block:
    <?
    
  2. Create a variable to hold the result of the mysql_connect() function. Include the @ to suppress warnings, as well as the die() function to cause the script to end and a message to display if the connection fails:
    $connection = @mysql_connect("localhost", "spike", "9sj7En4")
    or die(mysql_error());
    
    
  3. Create a variable to hold the result of the mysql_list_dbs() function. Include the @ to suppress warnings, as well as the die() function to cause the script to end and a message to display if the script can't get the list:
    $dbs = @mysql_list_dbs($connection) or die(mysql_error());
     
    The only argument necessary for the mysql_list_dbs() function is the link identifier for the current connection.

    1. You'll be looping through a result and dynamically populating a bullet list. Start that bullet list outside the loop:
      $db_list = "<ul>";
      
    2. Start a counter. You'll need it for your loop:
      $i = 0;
      
    3. Begin a while loop. This loop will continue for as long as the value of $i is less than the number of rows in the $dbs result value:
      while ($i < mysql_num_rows($dbs)) {
      
    4. Once you're within the while loop, get the name of the database reflected in the current row of the result:
      $db_names[$i] = mysql_tablename($dbs, $i); 
       
      1. The variable $i is replaced by its value, so during the first loop this line would be something like $db_names[0] = mysql_tablename($dbs, 0);
        Counting starts at 0, not 1, so this would reflect the first row in the result. As the counter increments, so does the row number.
      2. Add the current database name to the bullet list:
        $db_list .= "<li>$db_names[$i]";
        
      3. Increment your count before you close the while loop:
        $i++;
        
        
      4. Close the while loop, the bullet list, and your PHP block:
        }
        $db_list .= "</ul>";
        ?>