我正在尝试显示每个表的所有字段并将它们分配给多级数组,但我得到'在非对象上调用成员函数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'];
}
}
谢谢!
答案 0 :(得分:2)
由于$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.