php - 在 foreach 循环中显示来自的列

标签 php mysql mysqli

我试图显示每个表的所有字段并将它们分配给多级数组,但我得到“调用非对象上的成员函数 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];
     }
} 

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

旁注:可以作为创可贴解决方案:

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

关于php - 在 foreach 循环中显示来自的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757010/

相关文章:

c# - PHP 中的命名参数

php - 在购物车 Woocommerce 中添加产品简短描述

php - 避免重复条目 MySQL 和 PHP

mysql - mysqli连接仅在硬编码时有效

PHP/MySQL 验证列中是否存在值

php - 山魈轨道打开不工作

javascript - 如何根据单元格值删除html中的行

mysql - 高效的 MySQL/Eloquent 查询通过超过 1 个标签过滤帖子

php - 计算特定数据数除以总数据数

mysql - 需要 SQL View 创建查询帮助