【发布时间】:2011-06-10 02:07:33
【问题描述】:
我在一个 mysql 数据库中有许多表。我需要将表名存储在一个变量中并在每个表名上运行一些代码。
我该怎么做?
【问题讨论】:
我在一个 mysql 数据库中有许多表。我需要将表名存储在一个变量中并在每个表名上运行一些代码。
我该怎么做?
【问题讨论】:
使用它会直接给你表格数组,而不需要循环结果:
$pdo = new PDO('mysql:dbname=mydb', 'myuser', 'mypass');
$tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN, 0);
【讨论】:
使用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
}
}
【讨论】:
这里是怎么做的。
<?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
【讨论】:
您可以使用以下查询SHOW TABLES FROM db_name 获取表列表。参见例如http://dev.mysql.com/doc/refman/5.5/en/show-tables.html.
【讨论】: