php-mysqlHow to list databases in PHP and MySQL?
To list databases in PHP and MySQL, you can use the SHOW DATABASES
command.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SHOW DATABASES";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Database: " . $row["Database"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Output example
Database: information_schema
Database: mysql
Database: performance_schema
Database: sys
Database: your_database_name
Code explanation
$servername = "localhost";
- sets the server name to localhost$username = "username";
- sets the username$password = "password";
- sets the password$conn = new mysqli($servername, $username, $password);
- creates a new connection to the MySQL server$sql = "SHOW DATABASES";
- sets the SQL query to show databases$result = $conn->query($sql);
- executes the queryif ($result->num_rows > 0) {
- checks if there are any resultswhile($row = $result->fetch_assoc()) {
- fetches the resultsecho "Database: " . $row["Database"]. "<br>";
- prints the database name$conn->close();
- closes the connection
Helpful links
More of Php Mysql
- How to join tables with PHP and MySQL?
- How to use a variable in a MySQL query using PHP?
- How to update to null value in MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to fetch data from MySQL in PHP?
- How to check if a record exists in PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to escape a string for MySQL in PHP?
- How to convert MySQL datetime to string in PHP?
- How to export data from MySQL to Excel using PHP?
See more codes...