遍历mysql数据库

问题描述:

我的服务器上有一系列mysql数据库.这些数据库的名称存储在单独的数据库表(用户)-column(dbname)中.我想遍历表(用户),获取dbname,连接到每个数据库,并对每个数据库执行操作.我该如何执行这样的循环?

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 (users), get the dbnames, connect to each and perform an operation on each database. How do I perform such looping?

经过几天的努力,我终于提出了这种解决方案.我从该平台上针对该问题提供的解决方案中汲取了很多想法.解决方案本身对我不起作用,但是我从中得到了很多想法.

After days of struggle I was able to come out with this solution. I took a lot of ideas from solutions that were provided to this question on this platform. the solutions themselves did not work for me but I had lots of ideas from them.

<?php

    //db parameters
    $dbhost = "myhost"; // this will ususally be 'localhost', but can sometimes differ  
    $dbname = "dbusers"; // the name of the database that you are going to use for this project  
    $dbuser = "root"; // the username that you created, or were given, to access your database  
    $dbpass = "mypassword"; // the password that you created, or were given, to access your database  


    // I first connect to the db with names of the other dbs 
    mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());  
    mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());  


    //select dbnames from the table with db names
    $query  = "SELECT dbname FROM users";
    $result = mysql_query($query);


    //loop through the results(dbname) and connect to each db 
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    //put the dbname results into a variable
    $dbName =$row['dbname'];
    // connect to each db
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());  
    $db = mysql_select_db("mydbprefix_".$dbName) ;



       //do a query for each db this is because each db has same tables and structure
   //check to see if db exist
      if( $db ){

   //all the operation goes here in my case I wanted to count number of products for each table called products.
      $query2 = mysql_query("SELECT * FROM products");

    $num_rows = mysql_num_rows($query2);
    $pro = $num_rows;
    echo "this user has ".$pro." products"."<br/>";

    //another operation goes here for the same db.

    // then close connection for each db
    mysql_Close ($conn);
    }
     } 
    ?>

这就是我解决此问题的方法.可能不是最好的解决方案,但这就是我所拥有的

This was how I went around this problem. It might not be the best solution but this is what I have