任何想法,以避免每当我想以安全的方式从数据库中获取数据重复这个冗长的乱码?php oop准备语句
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'"));
任何建议将有助于我!
请说明您的具体问题或添加额外的细节,以确切地突出你所需要的。正如目前所写,很难确切地说出你在问什么。请参阅[如何提问](http://stackoverflow.com/help/how-to-ask)页面以获得澄清此问题的帮助。 –
您可以将参数放在关联数组中,即$ params ='[id'=> $ id,'item_id'=> $ item_id]',并直接在execute语句中使用它。即''$ this - > _ query-> execute($ params);'然后按正常方式取回。 PDO将自动执行所有必需的绑定,因此您不需要。 –