How can I get a list of MySQL databases in PHP using PDO?

前端 未结 4 591
既然无缘
既然无缘 2020-12-16 16:13

I wonder how can I get the list of MySQL databases in PHP using PDO without having to connect to a database first ( I mean no dbname in dsn )?

Usually I used to use

相关标签:
4条回答
  • 2020-12-16 16:25

    Thanks nick rulez. I made an example of DBs listing:

    $user = 'root';
    $pass = 'root';
    $server = 'localhost';
    
    $dbh = new PDO( "mysql:host=$server", $user, $pass );
    $dbs = $dbh->query( 'SHOW DATABASES' );
    
    while( ( $db = $dbs->fetchColumn( 0 ) ) !== false )
    {
        echo $db.'<br>';
    }
    
    0 讨论(0)
  • 2020-12-16 16:25

    Another method similar to Falcon's:

    This script uses foreach instead of while and print instead of echo for the db names and the break tag is set up as it would be used with XML. It also uses the associative property, the column name, instead of the array index of the column in the returned row to display the desired result.

    This assumes you have the PDO connection properly set up and = $dbconn. Many times $db is used instead of $dbconn in examples.

    $stmt ="SHOW DATABASES";
    foreach($dbconn->query($stmt) as $row){
    print $row['Database'];echo"<br />";
    }
    
    0 讨论(0)
  • 2020-12-16 16:28

    You can use

    show databases
    

    or a query on the information_schema:

    select schema_name from information_schema.schemata
    
    0 讨论(0)
  • 2020-12-16 16:39
    try{
      $DBH = new PDO("mysql:host=localhost", "root", "");
      $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
      $DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }catch(PDOException $e) {
      echo "Fail";
    }
    
    $rs = $dbo->query("SHOW DATABASES");
    while ($h = $rs->fetch(PDO::FETCH_NUM)) {
       echo $r[0]."<br>";
    }
    
    0 讨论(0)
提交回复
热议问题