如何在PDO包装类中同时使用fetch()和fetchAll()


How to use both fetch() and fetchAll() in a PDO wrapper class?

如何更改我的PDO包装类,这样,如果我希望查询得到单行结果,它就会使用fetch((,如果它希望得到多个结果,它会使用fetchAll((。

现在,如果我只有一个结果,我仍然必须循环通过结果数组,这对我来说似乎很不可行

模型中的查询:

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()时,请明确选择它!没那么难
但是,当你在几个月后偶然发现这个代码时,你就会知道这个值意味着什么。

当您需要单行时,请使用一个方法来获取单行。当您需要多行时,请使用一个方法来获取多行
它简单明了!

当您在两个月后返回到您的代码时,您将完全不知道,您期望什么。所以-总是显式地编写它

下面是我的mysqli包装类的一个摘录,给你一个想法:

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;
}

看看-从函数名称,你总是可以判断出预期的结果:

$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($qry->rowCount() > 1){
            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);
            }
        }
        else{
            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 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);
    }
}