简体   繁体   中英

How can I retrieve a database name with PHP?

This is long-winded, but my current setup is a WordPress multisite that is distributed over 256 databases (performance reasons). When sites are generated, a script auto-populated the WP tables needed onto a randomly selected database. The science is beyond my understanding completely.

Anyways, I have a need to alter data on a table for one of my sites. I need to find out which database its table reside. A long while ago, I had success with this:

<?php
    $query="select database() AS <code>db</code>";
    $result=mysql_query($query);
    $row = mysql_fetch_assoc($result);
        echo 'database: '.$row['db'].'<p>';
?>

That no longer seems to function and looks like it has deprecated functions. Any help would be greatly appreciated. Thanks!

If you're using mysqli_ you can do this -

if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

That returns the name of the default database for this connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM