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);
精彩评论