How to get a list of databases?

前端 未结 4 641
醉梦人生
醉梦人生 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 00:54

    Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:

    $mysqli = ... // This object is my equivalent of Rick's $link object.
    
    $sql = "SHOW DATABASES";
    $result = $mysqli->query($sql);
    if ($result === false) {
        throw new Exception("Could not execute query: " . $mysqli->error);
    }
    
    $db_names = array();
    while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
        $db_names[] = $row[0]; // Add db name to $db_names array
    }
    
    echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
    

提交回复
热议问题