How to get a list of databases?

前端 未结 4 651
醉梦人生
醉梦人生 2020-12-17 00:34

I was wondering if there\'s a way in PHP to list all available databases by usage of mysqli. The following works smooth in

4条回答
  •  一个人的身影
    2020-12-17 01:15

    Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.

    first you have to make database connection in OOP

    //error reporting Procedural way
    //mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 
    
    //error reporting OOP way
    $driver = new mysqli_driver();
    $driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
    
    $conn = new mysqli("localhost","root","kasun12345");
    

    using Index array of search result

    $dbtoSkip = array("information_schema","mysql","performance_schema","sys");
    
    $result = $conn->query("show databases");
    while($row = $result->fetch_array(MYSQLI_NUM)){
        $print = true;
    
        foreach($dbtoSkip as $key=>$vlue){
            if($row[0] == $vlue) {
                $print=false;
                unset($dbtoSkip[$key]);
            }
        }
    
        if($print){
            echo '
    '.$row[0]; } }

    same with Assoc array of search result

    $dbtoSkip = array("information_schema","mysql","performance_schema","sys"); 
    
    $result = $conn->query("show databases");
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $print = true;
    
        foreach($dbtoSkip as $key=>$vlue){
            if($row["Database"] == $vlue) {
                $print=false;
                unset($dbtoSkip[$key]);
            }
        }
    
        if($print){
            echo '
    '.$row["Database"]; } }

    same using object of search result

    $dbtoSkip = array("information_schema","mysql","performance_schema","sys"); 
    
    $result = $conn->query("show databases");
    while($obj = $result->fetch_object()){
        $print = true;
        foreach($dbtoSkip as $key=>$vlue){
            if( $obj->Database == $vlue) {
                $print=false;
                unset($dbtoSkip[$key]);
            }
        }
    
        if($print){
            echo '
    '. $obj->Database; } }

提交回复
热议问题