2016-12-31 6 views
0

現在、自分のカスタムデータベースクラスを作成しようとしています。これは、データベースの挿入、更新、選択などの基本的な操作を可能にします。私は、私の挿入機能のために働いているコードを持っているが、それは2回挿入されていると私はなぜわからない。シングルトンのパターンを乱して、今日はかなりの問題を抱えているので、しばらくしています。どんな助けも素晴らしいだろう。ありがとうカスタムPDOデータベースクラス内で2回クエリが実行されます

ここでの問題の方法は、メソッドです。 db()メソッドを使用して、データベース接続のインスタンスを取得します。このコードDatabase::Insert

Database::insert("test_table", [ 
    'username' => "Joe_Scotto", 
    'name' => "Joe" 
]); 

を呼び出す

database.phpで

class Database { 
    // Class Properties 
    private static $_instance; 
    public $pdo; 

    /** 
    * Returns a database connection 
    * @return resource Database Connection 
    */ 
    private static function db() { 
     // Return Database Connection 
     return Database::getInstance()->getConnection(); 
    } 

    private function getConnectionProperties($property) { 
     return $GLOBALS['config']['database'][$property]; 
    } 

    /** 
    * Singleton for database connection 
    * @return class Returns one instance of the Database class 
    */ 
    public static function getInstance() { 
     if(!self::$_instance) { 
      self::$_instance = new self(); 
     } 
     return self::$_instance; 
    } 

    /** 
    * Connects to database 
    * @return mysql PDO connection to mysql databse 
    */ 
    public function getConnection() { 
     try { 
      //Attempt to connect 
      $this->pdo = new PDO('mysql:host=' . $this->getConnectionProperties('host') . ';dbname=' . $this->getConnectionProperties('database') , $this->getConnectionProperties('username'), $this->getConnectionProperties('password')); 

      //Return connection 
      return $this->pdo; 
     } catch (PDOException $e) { 
      throw new PDOException($e); 
     } 
    } 

    public static function insert($table, $params) { 
     // Define initial query 
     $query = "INSERT INTO `{$table}` ("; 

     // Format rows to insert 
     foreach(array_keys($params) as $field) { 
      $fields .= $field . ","; 
      $bindParams .= ":" . $field . ","; 
     } 

     // Add rows and bind params to query 
     $query .= rtrim($fields, ',') . ") VALUES(" . rtrim($bindParams, ',') . ")"; 

     // Prepare Query 
     $preparedQuery = self::db()->prepare($query); 

     foreach($params as $key => $value) { 
      $queryParams[':' . $key] = $value; 
     } 

     //Execute Query 
     if($preparedQuery->execute($queryParams)) { 

     } 
    } 
} 

が作業を行い、唯一の問題は、それが二回実行されることです。私はこれは、クラスが2回インスタンス化されることと関係があると思いますが、わかりません。

+0

あなたのシングルトンパターンは基本的に大丈夫です。このコードを掘り下げる前に( 'execute()'を繰り返す明白な兆候は見られません)、スクリプト全体が2回呼び出されていないことを確認しましたか? CLIではなくWebブラウザでこれを実行していると仮定すると、間違った書き換えルール、 '

関連する問題