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