如何更改我的PDO包装类,以便如果我期望单行结果与我的查询它使用fetch(),并且如果它期望多个结果它使用fetchAll()。如何在PDO包装类中同时使用fetch()和fetchAll()?
现在,如果我只有一个结果,我仍然通过结果数组必须循环,并且似乎非常unpracticable给我。
查询模型:
public function doccEdit() {
$id = mysql_real_escape_string($_GET['id']);
$this->result = $GLOBALS['db']->select("creditcards", "id = ?", $id);
print_r($this->result);
}
在包装类:
public function run($sql, $bind="") {
$this->sql = trim($sql);
$this->bind = $this->cleanup($bind);
$this->error = "";
try {
$pdostmt = $this->prepare($this->sql);
if($pdostmt->execute($this->bind) !== false) {
if(preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
return $pdostmt->fetchall(PDO::FETCH_OBJ);
elseif(preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this->sql))
return $pdostmt->rowCount();
}
} catch (PDOException $e) {
$this->error = $e->getMessage();
$this->debug();
return false;
}
}
你为什么不只是总是使用fetchall()?如果只有一排,你会得到一个...... – Ben 2013-02-23 14:09:33
因为我认为我可以避免循环。使用fetchall,即使只有一个结果,我也必须使用循环。 – 2013-02-23 14:15:50
mysql_real_escape_string在这里做什么?你是否正确地格式化了“creditcards”? – 2013-02-23 14:32:13