2016-08-04 106 views
1

我試圖顯示每個表的所有字段,並將它們分配給一個多級別的數組,但我得到'調用成員函數fetch_assoc()在非對象'...顯示列在foreach循環

$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']; 
    } 
}  

謝謝!

回答

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. 
+0

旁註:在';'分號在不需要在查詢語句 – Ghost

+0

謝謝您的回答。對不起,我可能不是很精確,我在'while($ row_fields = $ result_fields ... line')出現錯誤,我將編輯這個問題......我試圖在數據庫函數... – codeispoetry

+0

@codeispoetry是的我已經測試了代碼錯誤,錯誤被列隊鏈接,原點錯誤地獲取表,獲取正確的表,列將正確提取 – Ghost