【问题标题】:Get list of MySQL tables and run a code for every table获取 MySQL 表列表并为每个表运行代码
【发布时间】:2011-06-10 02:07:33
【问题描述】:

我在一个 mysql 数据库中有许多表。我需要将表名存储在一个变量中并在每个表名上运行一些代码。

我该怎么做?

【问题讨论】:

    标签: php mysql for-loop


    【解决方案1】:

    使用它会直接给你表格数组,而不需要循环结果:

    $pdo = new PDO('mysql:dbname=mydb', 'myuser', 'mypass'); 
    $tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN, 0);
    

    【讨论】:

      【解决方案2】:

      使用SHOW TABLES:

      $pdo = new PDO('mysql:dbname=mydb', 'myuser', 'mypass');
      $stmt = $pdo->query('SHOW TABLES;');
      
      if ($stmt->rowCount() > 0) {
          $tables = $stmt->fetchAll(PDO::FETCH_NUM);
          foreach ($tables as $table) {
              $table_name = $table[0];
              // do something
          }
      }
      

      【讨论】:

        【解决方案3】:

        这里是怎么做的。

        <?php
        
            $mysqli = new MySQLi (..); //add ur account details here
        
            $result = $mysqli -> query ("SHOW TABLES");
            $tables = array();
            while ($row = $result -> fetch_assoc()){
                $tables[] = $row[0];
            }
        
            foreach ( $tables as $table ){
                // do your processing on tables.
            }
        

        更多信息show tables: MySQL :: MySQL 5.5 Reference Manual :: 12.4.5.38 SHOW TABLES Syntax

        【讨论】:

        • 您不需要 foreach,因为您可以在 while 循环中执行此操作,但 +1
        • @RobertPitt;是的,您可以,但是这样您就可以在外部使用列表,例如,将列表作为表名数组发送到函数等。我只是认为以这种方式编写它会更具可扩展性。 :)
        【解决方案4】:

        您可以使用以下查询SHOW TABLES FROM db_name 获取表列表。参见例如http://dev.mysql.com/doc/refman/5.5/en/show-tables.html.

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-11
          • 2014-02-17
          • 1970-01-01
          • 1970-01-01
          • 2011-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多