Php 如何在PDO包装类中同时使用fetch()和fetchAll()?
我如何修改我的PDO包装类,以便如果我希望查询得到一行结果,它将使用fetch(),如果它需要多个结果,它将使用fetchAll() 现在,如果我只有一个结果,我仍然需要循环遍历结果数组,这对我来说是不现实的 模型中的查询:Php 如何在PDO包装类中同时使用fetch()和fetchAll()?,php,pdo,fetch,fetchall,Php,Pdo,Fetch,Fetchall,我如何修改我的PDO包装类,以便如果我希望查询得到一行结果,它将使用fetch(),如果它需要多个结果,它将使用fetchAll() 现在,如果我只有一个结果,我仍然需要循环遍历结果数组,这对我来说是不现实的 模型中的查询: public function doccEdit() { $id = mysql_real_escape_string($_GET['id']); $this->result = $GLOBALS['db']->select("creditc
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;
}
}
不要尝试将所有事情自动化 代码的魔力越小,支持就越容易,麻烦就越少。
不要试图将所有逻辑塞进一个方法中。这是一门课!您可以根据需要创建任意多的方法 当您需要
rowCount()
时,请明确选择它!没那么难。但是,当您在几个月后偶然发现这个代码时,您就会知道这个值意味着什么 当需要单行时-使用方法获取单行。 当需要多行时-使用一种方法获取多行。
它很简单,而且非常明确 当您在2个月后返回代码时,您将完全不知道您期望的是什么。所以-总是明确地写出来。 以下是我的文章的一个节选,给你一个想法:
public function query()
{
return $this->rawQuery($this->prepareQuery(func_get_args()));
}
/**
* Helper function to get scalar value right out of query and optional arguments
*
* Examples:
* $name = $db->getOne("SELECT name FROM table WHERE id=1");
* $name = $db->getOne("SELECT name FROM table WHERE id=?i", $id);
*
* @param string $query - an SQL query with placeholders
* @param mixed $arg,... unlimited number of arguments to match placeholders in the query
* @return string|FALSE either first column of the first row of resultset or FALSE if none found
*/
public function getOne()
{
$query = $this->prepareQuery(func_get_args());
if ($res = $this->rawQuery($query))
{
$row = $this->fetch($res);
if (is_array($row)) {
return reset($row);
}
$this->free($res);
}
return FALSE;
}
/**
* Helper function to get single row right out of query and optional arguments
*
* Examples:
* $data = $db->getRow("SELECT * FROM table WHERE id=1");
* $data = $db->getOne("SELECT * FROM table WHERE id=?i", $id);
*
* @param string $query - an SQL query with placeholders
* @param mixed $arg,... unlimited number of arguments to match placeholders in the query
* @return array|FALSE either associative array contains first row of resultset or FALSE if none found
*/
public function getRow()
{
$query = $this->prepareQuery(func_get_args());
if ($res = $this->rawQuery($query)) {
$ret = $this->fetch($res);
$this->free($res);
return $ret;
}
return FALSE;
}
/**
* Helper function to get single column right out of query and optional arguments
*
* Examples:
* $ids = $db->getCol("SELECT id FROM table WHERE cat=1");
* $ids = $db->getCol("SELECT id FROM tags WHERE tagname = ?s", $tag);
*
* @param string $query - an SQL query with placeholders
* @param mixed $arg,... unlimited number of arguments to match placeholders in the query
* @return array|FALSE either enumerated array of first fields of all rows of resultset or FALSE if none found
*/
public function getCol()
{
$ret = array();
$query = $this->prepareQuery(func_get_args());
if ( $res = $this->rawQuery($query) )
{
while($row = $this->fetch($res))
{
$ret[] = reset($row);
}
$this->free($res);
}
return $ret;
}
/**
* Helper function to get all the rows of resultset right out of query and optional arguments
*
* Examples:
* $data = $db->getAll("SELECT * FROM table");
* $data = $db->getAll("SELECT * FROM table LIMIT ?i,?i", $start, $rows);
*
* @param string $query - an SQL query with placeholders
* @param mixed $arg,... unlimited number of arguments to match placeholders in the query
* @return array enumerated 2d array contains the resultset. Empty if no rows found.
*/
public function getAll()
{
$ret = array();
$query = $this->prepareQuery(func_get_args());
if ( $res = $this->rawQuery($query) )
{
while($row = $this->fetch($res))
{
$ret[] = $row;
}
$this->free($res);
}
return $ret;
}
Look-从函数名中,您始终可以知道预期的结果:
$name = $db->getOne('SELECT name FROM table WHERE id = ?i',$_GET['id']);
$data = $db->getAll("SELECT * FROM ?n WHERE mod=?s LIMIT ?i",$table,$mod,$limit);
不要被返回行数这样的陷阱所愚弄。结果集中可能有一行您想要填充的
fetchAll
。因此,它将返回一维数组而不是多维数组,并且您的页面上会有大量视频效果,因为您没有将答案标记为已接受。我想我会回答你的问题。我是在自己寻找答案时发现的。我同意“你的常识”,它们应该是两个独立的功能。然而,作为对您问题的直接回答,这就是我所拥有的(PDO示例,而不是mysqli):
但是,我发现如果查询表中的所有行,但表中只有一行,那么它将返回一维数组而不是二维数组。我处理结果的代码不适用于这两种类型的数组。我每次都可以处理这个问题,但我发现,如上所述,将它们分成不同的函数更容易,因此如果我知道只有一个答案,我可以调用相应的函数。这就是我现在拥有的:
function select($sql,$params=NULL,$fetchType=NULL){
try{
$qry = $this->db->prepare($sql);
$qry->execute($params);
if($fetchType == 'OBJ'){//returns object
$results = $qry->fetch(PDO::FETCH_OBJ);
}elseif($fetchType == 'NUM'){//-numerical array
$results = $qry->fetch(PDO::FETCH_NUM);
}else{//default - associative array
$results = $qry->fetch(PDO::FETCH_ASSOC);
}
if($results){
return $results;
}else{
return NULL;
}
}
catch(PDOException $err){
$this->logError($err);
}
}
function selectAll($sql,$params=NULL,$fetchType=NULL){
try{
$qry = $this->db->prepare($sql);
$qry->execute($params);
if($fetchType == 'OBJ'){//returns object
$results = $qry->fetchAll(PDO::FETCH_OBJ);
}elseif($fetchType == 'NUM'){//-numerical array
$results = $qry->fetchAll(PDO::FETCH_NUM);
}else{//default - associative array
$results = $qry->fetchAll(PDO::FETCH_ASSOC);
}
if($results){
return $results;
}else{
return NULL;
}
}
catch(PDOException $err){
$this->logError($err);
}
}
你为什么不总是抓取所有()?如果只有一行,你会得到一行…因为我想我可以避免循环。使用fetchall,即使只有一个结果,我也必须使用循环。mysql\u real\u escape\u string在这里做什么?你能正确地格式化“信用卡”吗?我就是受不了这么多重复的代码。你肯定需要学习如何使用函数。有没有办法将函数名保存在变量中?(将“fetch”替换为“fetchAll”)?这样做没有单一的理由。谢谢,你很有帮助。
function select($sql,$params=NULL,$fetchType=NULL){
try{
$qry = $this->db->prepare($sql);
$qry->execute($params);
if($fetchType == 'OBJ'){//returns object
$results = $qry->fetch(PDO::FETCH_OBJ);
}elseif($fetchType == 'NUM'){//-numerical array
$results = $qry->fetch(PDO::FETCH_NUM);
}else{//default - associative array
$results = $qry->fetch(PDO::FETCH_ASSOC);
}
if($results){
return $results;
}else{
return NULL;
}
}
catch(PDOException $err){
$this->logError($err);
}
}
function selectAll($sql,$params=NULL,$fetchType=NULL){
try{
$qry = $this->db->prepare($sql);
$qry->execute($params);
if($fetchType == 'OBJ'){//returns object
$results = $qry->fetchAll(PDO::FETCH_OBJ);
}elseif($fetchType == 'NUM'){//-numerical array
$results = $qry->fetchAll(PDO::FETCH_NUM);
}else{//default - associative array
$results = $qry->fetchAll(PDO::FETCH_ASSOC);
}
if($results){
return $results;
}else{
return NULL;
}
}
catch(PDOException $err){
$this->logError($err);
}
}