当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Get list of MySQL tables and run a code for every table

问题描述:

I have a number of tables in one mysql database. I need to store the table name in a variable and run some code on each table name.

How can I do that?

网友答案:

Use 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
    }
}
网友答案:

Here is how to do it.

<?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.
    }

More info on show tables: MySQL :: MySQL 5.5 Reference Manual :: 12.4.5.38 SHOW TABLES Syntax

网友答案:

You can obtain a list of tables with the following query SHOW TABLES FROM db_name. See e.g. http://dev.mysql.com/doc/refman/5.5/en/show-tables.html.

网友答案:

Using this will give you directly the array of tables, without the need to cycle on result:

$pdo = new PDO('mysql:dbname=mydb', 'myuser', 'mypass'); 
$tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN, 0);
分享给朋友:
您可能感兴趣的文章:
随机阅读: