2012-11-09 24 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