Looping through mysql database

后端 未结 3 1944
慢半拍i
慢半拍i 2021-01-27 20:32

I have series of mysql databases on my server. The names of these databases are stored in a separate database table (users) - column(dbname) . I want to loop through table (user

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 20:59

    i would do something like this, good luck! :

    function dbConnect($location, $username, $password, $database) {
        $conn = mysql_connect($location, $username, $password); 
        if (!$conn) die ("Could not connect MySQL"); 
        mysql_select_db($database, $conn) or die ("Could not open database ".$database);
    }
    #######
    # Connexion to databases containing users (add your own fields)
    #######
    
    
    dbConnect('localhost', 'root', '', 'databases');
    
    $sql = "SELECT * FROM users";
    $result = mysql_query($sql);
    $numrows = mysql_num_rows($result);
    
    #######
    # Looping to establish connexion to db1 and db2
    #######
    while($row = mysql_fetch_array($result)) {
        dbConnect('localhost', $row["user"], $row["pass"], $row["db"]);
    }
    
    #######
    # At this point, the connexion is established to LOCAHOST[DATABASES], LOCALHOST[DB1], LOCALHOST[DB2]
    #######
    
    $sql = "SELECT * FROM databases.users";
    $result = mysql_query($sql);
    $numrows = mysql_num_rows($result);
    while($row = mysql_fetch_array($result)) {
        print "
    ";
        print_r($row);
        print "
    "; } /* Array ( [id] => 1 [user] => root [pass] => [db] => db1 ) Array ( [id] => 2 [user] => root [pass] => [db] => db2 ) */ $sql = "SELECT * FROM db1.infos"; $result = mysql_query($sql); $numrows = mysql_num_rows($result); while($row = mysql_fetch_array($result)) { print "
    ";
        print_r($row);
        print "
    "; } /* Array ( [id] => 1 [name] => John [age] => 26 ) Array ( [id] => 2 [name] => Henri [age] => 34 ) */ $sql = "SELECT * FROM db2.infos"; $result = mysql_query($sql); $numrows = mysql_num_rows($result); while($row = mysql_fetch_array($result)) { print "
    ";
        print_r($row);
        print "
    "; } /* Array ( [id] => 1 [name] => Paul [age] => 30 ) Array ( [id] => 2 [name] => Scott [age] => 39 ) */

提交回复
热议问题