我最近正在做一些数据库维护,旨在对某些事情进行一些错误检查和保护,我可以列出表并将它们存储在一个数组中而没有问题,但是当我尝试验证该字段时出现了我的问题桌子......它确实有效 - 但在第二次询问时。我错过了什么,或者这是 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
我尝试使用 $this-> 将静态变量替换为公共变量来调用,但仍然得到相同的结果。我错过了什么还是这是一个错误?