开发者

How to show MySQL databases on a PHP script?

I want to display a list of all the databases on my server, when I do this:

echo mysql_query(" SHOW DATABASES ");

I get this error:

Resource id #3

So how to 开发者_StackOverflow中文版do it?


You need to retrieve a result set from the query, like so:

$set = mysql_query('SHOW DATABASES;');
$dbs = array();
while($db = mysql_fetch_row($set))
   $dbs[] = $db[0];
echo implode('<br/>', $dbs);


It's clear that you're new to PHP, so here's a huge tip.

The "mysql" extension is old and busted. Don't use it, and stop reading any tutorials that tell you it's the thing to use.

Instead, learn PDO, it works for most database engine and helps you do the right thing. Here's an example:

$dbh = new PDO('mysql:host=localhost;user=foo;password=bar;dbname=baz');
$statement = $dbh->query('SHOW DATABASES');
print_r( $statement->fetchAll() );


Jacob Relkin's solution is very good.

However, if you are using MySQL 5.x, I would only change one thing:

Instead of using SHOW DATABASES; I would use this query

SELECT schema_name FROM information_schema.schemata;


To list just the useful Databases, and not the system ones:

$query = "SELECT schema_name FROM information_schema.schemata WHERE schema_name
    NOT IN ('information_schema', 'mysql', 'performance_schema')";

$result = mysqli_query($link, $query) or die(mysqli_error($link));
$dbs = array();
while($db = mysqli_fetch_row($result))
   $dbs[] = $db[0];
echo implode('<br/>', $dbs);

Your MySQL user should have full access, otherwise you will see only the databases where you have at least read permissions.


you're getting a query result set. You need to retrieve the result rows like this:

$r = mysql_query("SHOW DATABASES");
while ($row = mysql_fetch_assoc($r)) {
    print_r($row);
}

that aught to do it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜