私は安全な方法でデータベースからデータを取得するたびに、この長い乱雑なコードを繰り返すことを避けるための考え方はありますか?php oop prepare文
public function test($param) {
$sql = "SELECT * FROM users WHERE id = :id AND item_id :item_id";
$this->_query = $this->_db->pdo()->prepare($sql);
$this->_query->bindValue(':id', $param);
$this->_query->bindValue(':item_id', $parmas);
$this->_query->execute();
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
}
は、私はまだないクラスの構造関数で定義されている。この
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
if(count($params)) {
//outside of the loop
$x = 1;
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
PDOのような単純なもののために周りの混乱に良い方法を作成しました。
//ここに詳細を追加するとこれが何をしようとしているのですか?
public function example($table, $params = array(), $extn = array(), $values = array()) {
$x = '';
$y = 0;
foreach($params as $param) {
$x .= $param;
if($y < count($params)) {
$x .= $extn[$y];
}
$y++;
}
$sql = "SELECT * FROM {$table} WHERE {$x}";
$this->_query = $this->_pdo->prepare($sql);
foreach($values as $value) {
$this->_query->bindValue($value);
}
$this->_query->execute();
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
}
が、イムこのエラー警告取得:PDOStatementに:: bindValue()は、少なくとも2つのパラメータ、ダウン
$test = new Example();
$test->example('users', array('id = :id', 'username = :username', 'id = :username', 'username = :id'), array(' AND ', ' OR ', ' AND '), array("':id', 4", "':username', 'alex'"));
以下のこのコードの 任意の提案は私には参考になる見込ん!
具体的な問題を明確にしたり、詳細を追加して必要なものを正確に強調してください。現在書かれているとおり、あなたが求めていることを正確に伝えるのは難しいです。この質問を明らかにするには、[How to Ask](http://stackoverflow.com/help/how-to-ask)ページを参照してください。 –
関連する配列、つまり$ params = '[id '=> $ id、' item_id '=> $ item_id]'の中にパラメータを置いて、それを直接execute文で使用することができます。すなわち、 '' $ this - > _ query-> execute($ params); 'それから、通常どおりにフェッチしてください。 PDOは自動的に必要なバインディングをすべて実行し、必要がないようにします。 –