我试图将所有SQL表和列拉出到数组中,应该如下所示:
array(
'tableName' => array(
'column1',
'column2',
'column3',
)
);
我编写了这段代码,用于从数据库中提取表名和列名并将其推送到数组。
<?php
include("db-config.php");
$method = $_SERVER['REQUEST_METHOD'];
$tablesQuery = mysqli_query($link,"SHOW TABLES");
echo '<pre>';
while($table = mysqli_fetch_assoc($tablesQuery)){
$tables[] = $table['Tables_in_'.$DB['database']];
}
for($i = 0;$i<count($tables);$i++){
$currentTable = $tables[$i];
$columnsQuery = mysqli_query($link,"DESCRIBE `".$currentTable."`");
while($column = mysqli_fetch_assoc($columnsQuery)){
$tables[$i][] = $column['Field']; //line 13
}
print_r($currentTable);
}
?>
第13行语法tables[$i]
一些如何转换为保持数组的字符串instand,这样就阻止了我推送列内的数据。
感谢你们的帮助!
答案 0 :(得分:1)
对于此任务,您需要查询INFORMATION_SCHEMA数据库和PDO to get the result in the proper format。
$sql = "SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='$DB[database]'";
$tables = $pdo->query($sql)->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);
会为您提供您想要的确切结果。
答案 1 :(得分:1)
您没有正确分配数组,因为$tables[$i]
是字符串值而不是数组键:
$currentTable = $tables[$i]; // $tables[$i] is a string: you use it as a string below
mysqli_query($link,"DESCRIBE `".$currentTable."`"); //$currentTable = used as string
然后在while循环中,尝试将该字符串用作数组键:
while($column = mysqli_fetch_assoc($columnsQuery)) {
$tables[$i][] = $column['Field']; //$tables[$i] == $currentTable as above = string
您需要做的是使用$ currentTable作为键来分配值:
while($column = mysqli_fetch_assoc($columnsQuery)) {
$tables[$currentTable][] = $column['Field'];
// or
$tables[$i][$currentTable][] = $column['Field'];