在foreach循环中显示COLUMNS FROM


SHOW COLUMNS FROM in foreach loop

我试图显示每个表的所有字段,并将它们分配给一个多级数组,但我得到了"对非对象上的成员函数fetch_assoc()的调用"。。。

$sql_tables = "SHOW TABLES;";
$result = $mysql->query($sql_tables );
if ($result->num_rows > 0) {
     while($row_tables = $result->fetch_assoc()) {
          $alltables_array[] = $row_tables["Tables_in_dbname"];
     }
} 
foreach ($alltables_array as $table) {
    $sql_fields = "SHOW COLUMNS FROM " . $table . ";";
    $result_fields= $mysql->query($sql_fields);
    while($row_fields = $result_fields->fetch_assoc()) { /* ERROR ON THIS LINE */
          $allfields_array[$table ][] = $row_fields['Field'];
    }
}    

谢谢!

由于$row_tables产生了您当前的数据库名称:

$row_tables["Tables_in_dbname"]; // this is incorrect (unless your current dbname is really dbname)
           // ^ undefined index

所以只需添加一个动态索引:

$dbname = 'test';
if ($result->num_rows > 0) {
     while($row_tables = $result->fetch_assoc()) {
          $alltables_array[] = $row_tables['Tables_in_' . $dbname];
     }
}

我建议使用->fetch_row()

if ($result->num_rows > 0) {
     while($row_tables = $result->fetch_row()) {
          $alltables_array[] = $row_tables[0];
     }
} 

然后指向索引0。无需在关联索引中添加动态变量。

旁注:可以是创可贴解决方案:

$alltables_array[] = $row_tables[key($row_tables)]; // not good though, it'll invoke key() every iteration.