1

私は最近データベースのメンテナンスを少し行っていて、特定のもののエラーチェックと保護を少し行うことを目指していました。テーブルを一覧表示して配列に格納できますが、そのフィールドを確認しようとすると問題が発生します。テーブル...それは機能しますが、2回目の質問です。私は何かを逃したことがありますか、それともこれは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->を使用して静的変数をパブリック変数に置き換えて呼び出しても、同じ結果が得られます。私は何かが足りないのですか、それともこれはバグですか?

4

1 に答える 1

1

$field問題は、関数を最初に呼び出すときに変数を上書きしていることです。

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

そのループ$fieldの最後に、期待する文字列ではなく、最後の値を持つ配列が含まれています。

同じテーブル名で2回目に関数を呼び出すと、そのセクションはスキップされself::$curTable === $tableます。

ループ内の変数の名前を変更するだけです。

foreach ($result as $i) {
   self::$dbTableFields[] = $i['Field'];
}
于 2012-11-09T01:49:28.990 に答える