Core PHP

List MySQL Databases

This PHP program displays example code that demonstrates how to list all of the databases via a MySQL query.

MySqlListDatabases.php

<?php
  $sServername = "127.0.0.1";
  $sUsername = "root";
  $sPassword = "MyPassword";

  try {
    // Create the connection object
    $qConnection = mysqli_connect($sServername, $sUsername, $sPassword);

    // Check that the connection is valid.
    if ($qConnection->connect_error) {
      die("Connection failed: " . $qConnection->connect_error);
    }

    $qSqlCommand = "SHOW databases";
    $qResult = $qConnection->query($qSqlCommand);

    // Output each row, which holds a database name
    if ($qResult->num_rows > 0) {
      // Output data for each row
      while($qRow = $qResult->fetch_assoc()) {
        foreach($qRow as $sDatabase) {
          echo $sDatabase;
        }
        echo "<br />";
      }
    }
    $qConnection->close();
  } catch(Exception $eException) {
    echo "error: " . $eException->getCode() . " " . $eException->getMessage();
  }
?>
 

Output

information_schema
mysql
mytestdb
school
test
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.