如何更改我的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