2012-11-09 73 views
1

我最近在做一個小小的數據庫維護,並且打算做一些錯誤檢查和保護某些事情,我可以列出表並將它們存儲在一個沒有問題的數組,但是當我嘗試驗證該表上的字段時,我的問題就出現了......它確實工作 - 但是在第二次詢問時。 我錯過了什麼,或者這是PHP內部的時間問題?

簡單表的創建:

CREATE TABLE `test_table` (
    `testfield1` int(11) NOT NULL AUTO_INCREMENT, 
    `testfield2` int(11) NULL, 
    `testfield3` int(11) NULL, 
    `testfield4` int(11) NULL, 
    PRIMARY KEY (`testfield1`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; 

剝離下來PHP代碼:

<?php 
include_once("config.php"); 

class dbController { 

    static $dbTables; 
    static $curTable; 
    static $dbTableFields; 

    protected $dbh; 

    function __construct() { 
     // DB_SERVER, DB_NAME, DB_USER + DB_PASS login credentials 
     // defined in config.php. 
     $this->dbh = new PDO(
      "mysql:host=". DB_SERVER .";dbname=" . DB_NAME, 
      DB_USER, 
      DB_PASS, 
      array(PDO::ATTR_PERSISTENT => true) 
     ); 

     // List the tables on the Database. 
     $sth = $this->dbh->query("SHOW TABLES"); 
     $result = $sth->fetchAll(PDO::FETCH_ASSOC); 
     foreach($result as $table) { 
      self::$dbTables[] = $table['Tables_in_' . DB_NAME]; 
     } 
    } 

    // Check field exists in table. 
    function check_fields($table, $field) { 

     if (in_array($table, self::$dbTables)) { 
      if (self::$curTable != $table) { 
       self::$curTable = $table; 
       $sth = $this->dbh->query("SHOW COLUMNS FROM `$table`"); 
       $result = $sth->fetchAll(PDO::FETCH_ASSOC); 
       foreach ($result as $field) { 
        self::$dbTableFields[] = $field['Field']; 
       } 
      } 
      return in_array($field, self::$dbTableFields) 
       ? "true<br />" : "false<br />"; 
     } 
    } 
} 

$db = new dbController(); 

// Calling the same command 3 times: 

echo $db->check_fields('test_table','testfield1'); 
echo $db->check_fields('test_table','testfield1'); 
echo $db->check_fields('test_table','testfield1'); 
?> 

而結果:

false 
true 
true 

我試圖用這個 - $>打電話,仍然得到同樣的結果一公共取代靜態變量。我錯過了什麼或者這是一個錯誤?

+1

檢查什麼的'自我:: $ dbTables'在構造函數的最後一刻。 – moonwave99

+0

echo "

"; print_r(dbController::$dbTables); echo "
";會生成數據庫上的表格數組。 – Lucas

回答

1

的問題是,你將要覆蓋$field變量第一次調用該函數:

function check_fields($table, $field) { 
    ... 
    foreach ($result as $field) { 
         ^^^^^^ 

在這個循環結束,$field包含的最後一個值,而不是你所期望的字符串數組它是。

第二次用相同的表名稱調用該函數時,該部分將跳過爲self::$curTable === $table

在環只要改變變量的名稱:

foreach ($result as $i) { 
    self::$dbTableFields[] = $i['Field']; 
} 
+0

和我_just_完成了在本地主機上設置這個數據庫和腳本以開始調試的工作。 -.- –

+0

@mmmshuddup對不起:-) – jeroen

+2

*抱怨*我知道這將是非常簡單(或愚蠢)的東西,我錯過了,謝謝! ;) – Lucas