Asked 7 years ago
12 Sep 2017
Views 1263
sarah

sarah posted

how to get list of database in PHP

i am using the mysql untill now but its deprecated from now so i am finding good way to get list of database in PHP with mysqli or PDO

so how to get list of database in PHP without mysql.
jassy

jassy
answered Apr 24 '23 00:00

To retrieve a list of databases in PHP, you can use the mysqli extension, which is a built-in extension for interacting with MySQL databases in PHP.

Here's an example code snippet to retrieve a list of databases using mysqli :



<?php

// Replace the values inside the single quotes with your own database credentials
$host = 'localhost';
$username = 'your-username';
$password = 'your-password';

// Create a new MySQLi object and connect to the MySQL server
$conn = new mysqli($host, $username, $password);

// Check for connection errors
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve the list of databases
$result = $conn->query("SHOW DATABASES");

// Iterate through the results and output each database name
while ($row = $result->fetch_assoc()) {
    echo $row['Database'] . "<br>";
}

// Close the database connection
$conn->close();

?>

In the above code, we first create a new my sqli object and connect to the MySQL server using the provided credentials. We then execute the SHOW DATABASES query to retrieve a list of all the databases on the server.

Finally, we loop through the results using the fetch_assoc () method to retrieve each database name, and output it to the browser. The database connection is then closed to release any resources used by the connection.

Note that this example assumes that you have the necessary permissions to access the databases on the MySQL server. If you don't have the necessary permissions, you may need to contact your database administrator or hosting provider for assistance.
Post Answer