2013-04-25 133 views
4

只是使用此功能,並沒有按計劃運行。它應該獲取數據庫中的所有表名並將它們存儲在一個數組中。然而,陣列的結果是增加了一倍在下面的例子中所示的陣列:PDO SHOW TABLES數組

Array ([0] => 113340) 
Array ([0] => 113340 [1] => 116516) 
Array ([0] => 113340 [1] => 116516 [2] => 139431) 
Array ([0] => 113340 [1] => 116516 [2] => 139431 [3] => 20731) 
Array ([0] => 113340 [1] => 116516 [2] => 139431 [3] => 20731 ...) 

的代碼,我使用:

function itemDiscontinued($dbh, $id, $detail) { 
    try { 
    $tableList = array(); 
    $result = $dbh->query("SHOW TABLES"); 
    while ($row = $result->fetch(PDO::FETCH_NUM)) { 
     $tableList[] = $row[0]; 
     print_r($tableList); 
    } 
    } 
    catch (PDOException $e) { 
    echo $e->getMessage(); 
    } 
} 
+2

+1刪除某人加入downvote。這個問題沒有錯,它是代碼中的一個簡單錯誤。用戶已經展示了研究和努力產生的問題,所以絕對不需要downvote! – 2013-04-25 11:47:59

回答

9

拿到表的所有名字,這是更好的

public function list_tables() 
{ 
    $sql = 'SHOW TABLES'; 
    if($this->is_connected) 
    { 
     $query = $this->pdo->query($sql); 
     return $query->fetchAll(PDO::FETCH_COLUMN); 
    } 
    return FALSE; 
} 
2

要打印在while循環數組!每次從記錄集中向其添加項目時,都會打印它。相反,你需要打印一次,它已經完成填充像這樣:

function itemDiscontinued($dbh, $id, $detail) { 
    try { 
     $tableList = array(); 
     $result = $dbh->query("SHOW TABLES"); 
     while ($row = $result->fetch(PDO::FETCH_NUM)) { 
      $tableList[] = $row[0]; 
     } 
     print_r($tableList); 
    } 
    catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 
} 
+0

啊這麼傻!我仍然在這裏學習,但無論如何非常感謝你本! – DrDog 2013-04-25 11:46:40

+1

@DDDOGN一點也不。最簡單的錯誤總是最難找到的! :-) – 2013-04-25 11:49:05